Javascript Textarea Tab Override
Topic
#24 by mreschke on 2008-01-30 23:17:11 (viewed 939 times)
Override tabs in a HTML textarea box.
The only problem with this script, is that if you are in a large textarea, where there are scroll bars, when you hit tab, \
it scrolls to the top, try it, it really sucks!
FIX: I fixed this scroll behavior, update this topic to reflect the changes
Also added other keys, like shift+enter saves the doc...
http://blog.riait.co.uk/2007/11/04/tab-aware-textarea/
<html>
<head>
<script type="text/javascript">
function TabAwareTextArea( o )
{
this._o = o;
this._isTabLast = false;
// for gecko:
this._restoreFocusWithCaret = -1;
this._lastCaretPosition = -1;
this.onObjectKeyDown = function(event)
{
var keyCode = ((window.event) ? window.event.keyCode : event.which );
this.handler._isTabLast = ( keyCode == 9 );
}
this.onObjectBlur = function(event)
{
if (this.handler._isTabLast)
{
this.handler._isTabLast = false;
this.focus();
if ( document.selection )
document.selection.createRange().text = "\t";
else
{
this.handler._lastCaretPosition = this.selectionEnd;
this.handler._restoreFocusWithCaret = setTimeout(
function (obj)
{
clearTimeout(obj.handler._restoreFocusWithCaret);
obj.handler._restoreFocusWithCaret = -1;
obj.focus();
var o = document.getElementById("txt");
var len = obj.selectionEnd;
obj.value = obj.value.substr( 0, len ) + "\t" + obj.value.substr( len );
obj.setSelectionRange(len+1,len+1);
},
10, this
);
}
}
}
this._o.handler = this;
if ( document.all )
{
this._o.onkeydown = this.onObjectKeyDown;
this._o.onblur = this.onObjectBlur;
}
else
{
this._o.addEventListener("keydown", this.onObjectKeyDown, false);
this._o.addEventListener("blur", this.onObjectBlur, false);
}
}
function init() {
new TabAwareTextArea( document.getElementById("theTextArea"));
}
</script>
</head>
<body onload="init();">
<textarea id='theTextArea' name='txtArea' rows='20' cols='80'></textarea>
</body>