Enabling Tabbing In A Textarea

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){
 if(navigator.userAgent.match("Gecko")){
  c=e.which;
 }else{
  c=e.keyCode;
 }
 if(c==9){
  replaceSelection(item,String.fromCharCode(9));
  document.getElementById(item.id).focus();
  return false;
 }
}
 
function setSelectionRange(input, selectionStart, selectionEnd){
 if(input.setSelectionRange){
  input.focus();
  input.setSelectionRange(selectionStart, selectionEnd);
 }else if(input.createTextRange){
  var range = input.createTextRange();
  range.collapse(true);
  range.moveEnd('character', selectionEnd);
  range.moveStart('character', selectionStart);
  range.select();
 }
}
 
function replaceSelection(input, replaceString){
 if(input.setSelectionRange){
  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);
  }else{
   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;
    if(!isCollapsed){
     range.moveStart('character', -replaceString.length);
     range.select();
    }
  }
 }
}

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.
CAPTCHA
3 + 11 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.