Here is how to Make the Tab Key Work in a TextArea (Javascript)
Monday, June 4th, 2007Here’s the code I came up with. It works in Firefox and IE but not in Safari.
Just place it anywhere on your page: (I included some comments in the code to explain the nonsense that’s going on there.)
<script type=\"text/javascript\" >
function tab_to_tab(e,el) {
//A function to capture a tab keypress in a textarea and insert 4 spaces and NOT change focus.
//9 is the tab key, except maybe it\'s 25 in Safari? oh well for them ...
if(e.keyCode==9){
var oldscroll = el.scrollTop; //So the scroll won't move after a tabbing
e.returnValue=false; //This doesn\'t seem to help anything, maybe it helps for IE
//Check if we\'re in a firefox deal
if (el.setSelectionRange) {
var pos_to_leave_caret=el.selectionStart+4;
//Put in the tab
el.value = el.value.substring(0,el.selectionStart) + \' \' + el.value.substring(el.selectionEnd,el.value.length);
//There\'s no easy way to have the focus stay in the textarea, below seems to work though
setTimeout(\"var t=document.getElementById(\'code1\'); t.focus(); t.setSelectionRange(\" + pos_to_leave_caret + \", \" + pos_to_leave_caret + \");\", 0);
}
//Handle IE
else {
// IE code, pretty simple really
document.selection.createRange().text=\' \';
}
el.scrollTop = oldscroll; //put back the scroll
}
}
</script>
Note: I used 4 spaces instead of a real tab, however if you’d prefer a real tab just replace the two places in the code above where it has four spaces enclosed in single quotes with String.fromCharCode(9)
Then make your text area look like this to active it:
<textarea name=\"code1\" id=\"code1\" onkeydown=\"tab_to_tab(event,document.getElementById(\'code1\'))\" ></textarea>
As shown here the textarea will need an id attribute which you will have to reference in second argument of the tab_to_tab function call.
My myraid of search terms to figure this stuff out:
- javascript tab inserts tab
- setTimeout
- document.selection has no properties
- document.selection.createRange firefox
- setSelectionRange
These two pages helped the most in devising this answer:
Tips For Typing Tab
Add tags to selected text in a textarea
Please post improvements in the comments. I’m still a Javascript baby.