Tuesday, December 30, 2008

JavaScript Tab in TextBox - for IE and Firefox

While seeking for a way to make tabs work in Firefox I found many code posts specific to Internet Explorer - this code below works in Mozilla Firefox as well for cross-browser tab functionality in a textarea.

The other code I found on the web was missing some functions I wanted like inserting the tab at the cursor location if in the middle of text and returning the cursor to the appropriate position instead of just sticking it at the end of the text after the tab has been inserted. Additionally I needed to scroll back to the cursor location in a textarea.

Additionally a lot of the examples seemed overly complicated. I wanted something simple so put common code in functions so reworked some of the examples I found to end up with the following:


<html>
<head>
<script type="text/javascript">
function doTab(arg1,arg2){
t=arg2
var k;

//save cursor position
var top= arg2.scrollTop;
var left= arg2.scrollLeft;

if ("which" in arg1){k=arg1.which}
else if("keyCode" in arg1){k=arg1.keyCode}
else if("keyCode" in window.event){k=window.event.keyCode }
else if ("which" in window.event){k=arg1.which}
else{return true}

//insert tab
if (k == 9) {
insertatcursor(t, "\t");
arg2.scrollTop = top;
arg2.scrollLeft = left;
return false;
}
return true
}

function insertatcursor(myField, myValue) {

//IE
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}

//Mozilla Firefox
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)+ myValue+ myField.value.substring(endPos, myField.value.length);
setSelRange(myField, endPos + myValue.length, endPos + myValue.length);
} else {
myField.value += myValue;
}
}

function setSelRange(inputEl, selStart, selEnd) {
if (inputEl.setSelectionRange) {
inputEl.focus();
inputEl.setSelectionRange(selStart, selEnd);
} else if (inputEl.createtextRange) {
var range = inputEl.createtextRange();
range.collapse(true);
range.moveEnd('character', selEnd);
range.moveStart('character', selStart);
range.select();
}
}

</script>
</head>

<body>
<textarea onkeydown="return doTab(event,this);"></textarea>
</body>
</html>