Last active
August 29, 2015 14:25
-
-
Save nikcorg/7d5c155bb6be1792dfe6 to your computer and use it in GitHub Desktop.
Tab key in Textarea
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Tab in form</title> | |
</head> | |
<body> | |
<form> | |
<textarea rows="15" cols="82">lorem ipsum | |
dolor sit amet | |
adipiscing elit | |
consectetuer</textarea> | |
</form> | |
<script> | |
var KEYCODE_TAB = 9; | |
var TAB = "\t"; | |
var NEWLINE = "\n"; | |
var area = document.getElementsByTagName("textarea")[0]; | |
function insertTab(textarea, selection) { | |
var caretPos = textarea.selectionStart; | |
var beforeCursor = textarea.value.substr(0, caretPos); | |
var afterCursor = textarea.value.substr(caretPos); | |
selection.start++; | |
selection.delta++; | |
textarea.value = beforeCursor + TAB + afterCursor; | |
} | |
function indentText(textarea, selection, indent) { | |
// Move selection start to the beginning of the first row | |
while (0 < selection.start && NEWLINE !== textarea.value.substr(selection.start - 1, 1)) { | |
selection.start--; | |
selection.length++; | |
} | |
var selectedText = textarea.value.substr(selection.start, selection.length); | |
var rows = selectedText.split(NEWLINE); | |
for (var i = 0, l = rows.length; i < l; i++) { | |
if (indent) { | |
rows[i] = TAB + rows[i]; | |
selection.delta++; | |
} else if (TAB === rows[i].substr(0, 1)) { | |
rows[i] = rows[i].substr(1); | |
selection.delta--; | |
} | |
} | |
var beforeSelection = textarea.value.substr(0, selection.start); | |
var afterSelection = textarea.value.substr(selection.end); | |
textarea.value = beforeSelection + rows.join(NEWLINE) + afterSelection; | |
} | |
function tabListener(evt) { | |
var selection = { | |
start: this.selectionStart, | |
end: this.selectionEnd, | |
length: this.selectionEnd - this.selectionStart, | |
delta: 0 | |
}, | |
indent = !evt.shiftKey; | |
if ("keyCode" in evt && KEYCODE_TAB === evt.keyCode) { | |
evt.preventDefault(); | |
if (indent && 0 === selection.length) { | |
insertTab(this, selection); | |
} else { | |
indentText(this, selection, indent); | |
} | |
this.setSelectionRange(selection.start, selection.end + selection.delta); | |
} | |
} | |
function initTabinput() { | |
window.addEventListener("keydown", tabListener.bind(area), false); | |
} | |
window.addEventListener("load", initTabinput, false); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Cleaning up old stuff. Storing some of it for sentimental reasons.