MattStypa.com
29Jun/10

Tabs in TEXTAREA

codeI was working on a small personal project the other day and I ran into a surprising obstacle. I wanted an online form to behave just like notepad does. Specifically I wanted to use tabs in a textarea of a form. The shocking part was how scarce the information on the issue was and how bizarre some approaches were. I ended up writing my own JavaScript to handle this issue and realized that my code works so well that I need to put it out there for others to use. You can check it out in action HERE.

Tested with: IE6, IE7, IE8, FireFox, Chrome, Safari, and Opera

Here is the business end that goes into the "HEAD" section.

<script type="text/javascript">
	// This script allows intuitive TAB functionality in HTML form fields.
	// Due to browser incompatibilities the following code has to be included in the field tags:
	// onkeydown="checkTab(event)"; onkeypress="operaTab(event)";
	// visit MattStypa.com for more information

	function checkTab(event)
	{
		// First we check if the key pressed was a tab
		if (event.keyCode == 9)
		{
			// Is this IE?
			if (navigator.appName == 'Microsoft Internet Explorer')
			{
				// This stops the default behavior of the tab key. preventDefault does not work in IE.
				event.returnValue = false;
				// This gets the current selection or cursor location
				range = document.selection.createRange();
				// Replaces the current selection with a tab character or simply inserts it at the current cursor position
				range.text = "\t";
				// This resets the selection
				range.collapse(true);
				// And this executes above statement.
				range.select();
			}
			else
			{
				// This stops the default behavior of the tab key
				event.preventDefault();
				// We need to save the current position of the cursor.
				var c = event.target.selectionStart;
				// Inserting a tab into the string.
				// First we grab what comes before the current selection (or cursor position).
				// Then we add the tab character. Finally we add the part the comes after the
				// current selection (or cursor position).
				event.target.value = event.target.value.slice(0,event.target.selectionStart).concat("\t").concat(event.target.value.slice(event.target.selectionEnd,event.target.value.length));
				// This sets the cursor position.
				event.target.selectionStart = c + 1;
				// And this cancels selection. Opera requires that this is on a seperate line.
				event.target.selectionEnd = c + 1;
			}
		}
	}

	function operaTab(event)
	{
		if (navigator.appName == 'Opera' && event.keyCode == 9)
		{
				// This stops the default behavior of the tab key
				// Opera is unable to do that when called from onkeydown
				event.preventDefault();
		}
	}
</script> 

Also we need to map some events to the field.

<textarea onkeydown="checkTab(event)"; onkeypress="operaTab(event)";></textarea>
  • Digg
  • Facebook
  • Twitter
Filed under: Code, Web Comments Off
Comments (0) Trackbacks (465)