Enabling Tabbing In A Textarea

20th June 2008 - 2 minutes read time

When a user presses the tab key in a browser window the normal action is for the user to move the focus to a different control. To enable a word processor like tab effect in a text area you need to catch the keystroke and add in the tab character to where ever the cursor is. This is the main issue with creating this solution, it is easy to add a tab to the end of the text, but most users might want to add a tab half way through the text.

Take the following HTML text area.

<textarea name="content" class="textarea" id="content" rows="20" cols="65"  wrap="on" onKeyDown="return catchTab(this,event)"></textarea>

When a keystroke is detected it runs the catchTab() function. This function detects if the keystroke is 9 (which means it is a tab) and runs the function called replaceSelection() in order to find out where the cursor is and replace the text that exists there.

function catchTab(item,e){
  return false;
function setSelectionRange(input, selectionStart, selectionEnd){
  input.setSelectionRange(selectionStart, selectionEnd);
 }else if(input.createTextRange){
  var range = input.createTextRange();
  range.moveEnd('character', selectionEnd);
  range.moveStart('character', selectionStart);
function replaceSelection(input, replaceString){
  var selectionStart = input.selectionStart;
  var selectionEnd = input.selectionEnd;
  input.value = input.value.substring(0, selectionStart)+ replaceString +   input.value.substring(selectionEnd);
  if(selectionStart != selectionEnd){
   setSelectionRange(input, selectionStart, selectionStart + 	replaceString.length);
   setSelectionRange(input, selectionStart + replaceString.length, selectionStart +    replaceString.length);
  }else if(document.selection){
   var range = document.selection.createRange();
   if(range.parentElement() == input){
    var isCollapsed = range.text == '';
    range.text = replaceString;
     range.moveStart('character', -replaceString.length);

With these functions in action the text area will act a little more like a word processor.

Add new comment

The content of this field is kept private and will not be shown publicly.