JavaScript - Enable Tabs In Textareas

Almost every web application that I have seen or used does not allow the user to use the TAB button in textareas to actually insert tabs. Instead it just moves the focus to the next element of the document. True, that is the intended way the browser uses tabs but today’s applications should be a little more user friendly.

When I am typing an article in a text editor I want to use tabs. When I am using the control panel of my hosting company to edit some code I for sure want to be able to use tabs.

So, to solve this problem I came up with the code below to enable that functionality. All you have to do is attach the keypressed function to the onkeydown event of the textarea.

e.g. document.getElementById(”textareaID”).onkeydown = keypressed;

Enjoy!

function keypressed(e)
{
	//get key pressed
	var key = null;
	if(window.event) key = event.keyCode;
	else if(e.which) key = e.which;

	//if tab pressed
	if(key != null && key == 9)
	{
		//IE
		if(document.selection)
		{
			//get focus
			this.focus();

			//get selection
			var sel = document.selection.createRange();

			//insert tab
			sel.text = "t";
		}
		//Mozilla + Netscape
		else if(this.selectionStart || this.selectionStart == "0")
		{
			//save scrollbar positions
			var scrollY = this.scrollTop;
			var scrollX = this.scrollLeft;

			//get current selection
			var start = this.selectionStart;
			var end = this.selectionEnd;

			//insert tab
			this.value = this.value.substring(0,start) + "t" + this.value.substring(end,this.value.length);

			//move cursor back to insert point
			this.focus();
			this.selectionStart = start+1;
			this.selectionEnd = start+1;

			//reset scrollbar position
			this.scrollTop = scrollY;
			this.scrollLeft = scrollX;
		}
		//time for a new browser!!!
		else this.value += "t";	

		//stop the real tab press
		return false;
	}
}