• How To?
  • Tips ‘n Tricks
  • WordPress
  • Snippets
  • Software
    • Browsers
    • Downloads
  • Web
  • Tools
    • Character Counter
    • chmod Calculator
    • Entities Encoder
    • Live HTML Editor
    • My IP
  • Contact
Twitter Facebook Google+ RSS
You are here: SumTips » Snippets » JavaScript Snippets » Enable Tab in HTML textarea Tag – JavaScript, jQuery & MooTools

Enable Tab in HTML textarea Tag – JavaScript, jQuery & MooTools

Posted on June 21, 2012 by Renji | Short URL: http://sumtips.com/?p=6884

By default when you press the tab key in a textarea, it moves to the next focusable element. If you’d like to alter this behavior instead to insert a tab character, it can be done using the codes shown in this post.

  • Using only JavaScript
  • Using jQuery
  • Using MooTools

Using only JavaScript

function insertTab(o, e)
{		
	var kC = e.keyCode ? e.keyCode : e.charCode ? e.charCode : e.which;
	if (kC == 9 && !e.shiftKey && !e.ctrlKey && !e.altKey)
	{
		var oS = o.scrollTop;
		if (o.setSelectionRange)
		{
			var sS = o.selectionStart;	
			var sE = o.selectionEnd;
			o.value = o.value.substring(0, sS) + "\t" + o.value.substr(sE);
			o.setSelectionRange(sS + 1, sS + 1);
			o.focus();
		}
		else if (o.createTextRange)
		{
			document.selection.createRange().text = "\t";
			e.returnValue = false;
		}
		o.scrollTop = oS;
		if (e.preventDefault)
		{
			e.preventDefault();
		}
		return false;
	}
	return true;
}

Add onkeydown event to the textarea

<textarea onkeydown="insertTab(this, event);"></textarea>

Source and Demo

Using jQuery

$("textarea").keydown(function(e) {
    if(e.keyCode === 9) { // tab was pressed
        // get caret position/selection
        var start = this.selectionStart;
            end = this.selectionEnd;

        var $this = $(this);

        // set textarea value to: text before caret + tab + text after caret
        $this.val($this.val().substring(0, start)
                    + "\t"
                    + $this.val().substring(end));

        // put caret at right position again
        this.selectionStart = this.selectionEnd = start + 1;

        // prevent the focus lose
        return false;
    }
});

Source and Demo

Using MooTools

In this method you can change the TAB key length by adjusting it in the code.

HTMLTextAreaElement.prototype.getCaretPosition=function(){return this.selectionStart};HTMLTextAreaElement.prototype.setCaretPosition=function(position){this.selectionStart=position;this.selectionEnd=position;this.focus()};HTMLTextAreaElement.prototype.hasSelection=function(){if(this.selectionStart==this.selectionEnd){return false}else{return true}};HTMLTextAreaElement.prototype.getSelectedText=function(){return this.value.substring(this.selectionStart,this.selectionEnd)};HTMLTextAreaElement.prototype.setSelection=function(start,end){this.selectionStart=start;this.selectionEnd=end;this.focus()};
    
    var textarea = document.getElementsByTagName('textarea')[0]; 
    
    textarea.onkeydown = function(event) {
        
        //support tab on textarea
        if (event.keyCode == 9) { //tab was pressed
            var newCaretPosition;
            newCaretPosition = textarea.getCaretPosition() + "    ".length;
            textarea.value = textarea.value.substring(0, textarea.getCaretPosition()) + "    " + textarea.value.substring(textarea.getCaretPosition(), textarea.value.length);
            textarea.setCaretPosition(newCaretPosition);
            return false;
        }
        if(event.keyCode == 8){ //backspace
            if (textarea.value.substring(textarea.getCaretPosition() - 4, textarea.getCaretPosition()) == "    ") { //it's a tab space
                var newCaretPosition;
                newCaretPosition = textarea.getCaretPosition() - 3;
                textarea.value = textarea.value.substring(0, textarea.getCaretPosition() - 3) + textarea.value.substring(textarea.getCaretPosition(), textarea.value.length);
                textarea.setCaretPosition(newCaretPosition);
            }
        }
        if(event.keyCode == 37){ //left arrow
            var newCaretPosition;
            if (textarea.value.substring(textarea.getCaretPosition() - 4, textarea.getCaretPosition()) == "    ") { //it's a tab space
                newCaretPosition = textarea.getCaretPosition() - 3;
                textarea.setCaretPosition(newCaretPosition);
            }    
        }
        if(event.keyCode == 39){ //right arrow
            var newCaretPosition;
            if (textarea.value.substring(textarea.getCaretPosition() + 4, textarea.getCaretPosition()) == "    ") { //it's a tab space
                newCaretPosition = textarea.getCaretPosition() + 3;
                textarea.setCaretPosition(newCaretPosition);
            }
        } 
    }

Source and Demo


Tweet

Related posts:

  • Prevent Copy, Cut and Paste into HTML Input Text Fields
  • Smooth Scroll to Page Top without an Anchor
  • Embed Google’s Pac Man Game on Your Website
  • Enable Auto-Resume Playback in Media Player Classic & Winamp
  • Give Your Site Visitors a Quick Print Preview Option, Ctrl+P Hotkey
Categories: JavaScript Snippets
Show-Hide Password in a Field

  • Get Updates via Email

  • Recent Posts

    • CMS2CMS: Migrate Site from Drupal or Joomla to WordPress
    • WordPress: Add Preview Button in Distraction Free Writing
    • How to Activate or Deactivate Individual Jetpack Modules
    • Windows 8: Auto Update Defender with Windows Update Disabled
    • Automatically Start and Close Programs at Specific Time
    • How to Copy Code from Notepad++ with Syntax Highlighting
  • Random Posts

    • Get Breadcrumb Navigation on any Site with Breadcrumb Navigator
    • Samsung Galaxy Tab 10.1 Features and Specifications
    • Identify Unknown File Types with Smart File Advisor
    • How to Copy Code from Notepad++ with Syntax Highlighting
    • Set External Source Viewer in Firefox, Opera and Internet Explorer
    • Windows Phone 7 Mango and iOS Skin Packs for Windows 7
  • Categories

    • Blogging
    • Games
    • Google
    • How To?
    • Linux
    • Microsoft
      • Windows
    • Miscellaneous
    • Phone
    • Snippets
      • AutoHotkey Snippets
      • CSS Snippets
      • htaccess Snippets
      • JavaScript Snippets
      • PowerShell Snippets
      • WordPress Snippets
    • Social
    • Software
      • Browsers
    • Tips 'n Tricks
    • Wallpapers
    • Web
© SumTips. Contact | Sitemap | Privacy Policy