Skip to content

Instantly share code, notes, and snippets.

@azappella
Last active December 11, 2015 10:28
Show Gist options
  • Save azappella/4587183 to your computer and use it in GitHub Desktop.
Save azappella/4587183 to your computer and use it in GitHub Desktop.
Catching Tabs in Textarea
<script>
function insertTab(o, e)
{
var kC = e.keyCode ? e.keyCode : e.charCode ? e.charCode : e.which;
if (kC == 9 && !e.shiftKey && !e.ctrlKey && !e.altKey)
{
var oS = o.scrollTop;
if (o.setSelectionRange)
{
var sS = o.selectionStart;
var sE = o.selectionEnd;
o.value = o.value.substring(0, sS) + "\t" + o.value.substr(sE);
o.setSelectionRange(sS + 1, sS + 1);
o.focus();
}
else if (o.createTextRange)
{
document.selection.createRange().text = "\t";
e.returnValue = false;
}
o.scrollTop = oS;
if (e.preventDefault)
{
e.preventDefault();
}
return false;
}
return true;
}
</script>
<textarea onkeydown="insertTab(this, event);"></textarea>
<textarea id="text-area" rows="20" cols="100"></textarea>
<script>
document.getElementById("text-area").onkeydown = function(e) {
if (!e && event.keyCode == 9)
{
event.returnValue = false;
insertAtCursor(document.getElementById("text-area"), " ");
}
else if (e.keyCode == 9)
{
e.preventDefault();
insertAtCursor(document.getElementById("text-area"), " ");
}
};
//http://alexking.org/blog/2003/06/02/inserting-at-the-cursor-using-javascript#comment-3817
function insertAtCursor(myField, myValue) {
//IE support
if (document.selection) {
var temp;
myField.focus();
sel = document.selection.createRange();
temp = sel.text.length;
sel.text = myValue;
if (myValue.length == 0) {
sel.moveStart('character', myValue.length);
sel.moveEnd('character', myValue.length);
} else {
sel.moveStart('character', -myValue.length + temp);
}
sel.select();
}
//MOZILLA/NETSCAPE support
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);
myField.selectionStart = startPos + myValue.length;
myField.selectionEnd = startPos + myValue.length;
} else {
myField.value += myValue;
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment