I want to check and see if the user's (blinking) cursor position is between two strings in a textarea.
Handling the tab events is it's own thing, I just want to know the method of handling the cursor location in relation to the tags.
I want to check and see if the user's (blinking) cursor position is between two strings in a textarea.
Handling the tab events is it's own thing, I just want to know the method of handling the cursor location in relation to the tags.
to find an inside-tag match, you can split the text into the left and right, then look for the proper open/close tags in the correct half. from there, it's simple to make the tab replacement using the same halfs:
<textarea>blah <code> this is the code </code> and this is not.</textarea>
<script>
function handleKeys(e) {
var t,n,s,r, pad=" ";
if (e.shiftKey && e.keyCode == 32) {
t = this.value,
n = this.selectionStart,
s = this.scrollTop,
r = [t.slice(0, n), t.slice(n)];
this.value = r.join(pad);
this.selectionStart = this.selectionEnd = n + pad.length;
this.scrollTop = s;
e.preventDefault();
}
}
</script>
pressing tab inside a code tag will insert a tab character. You should also consider providing some way for folks who use only the keyboard to escape the tab trap, maybe the escape key or something.
EDIT: i added scroll resume to fix a bug in some browsers that scroll the textarea to the top when inserting. Since it's an event that could fire a lot, i also optimized the function to ignore non-relevant key-presses completely (instead of doing some work each and every keydown).
tags. Then do math to know if the caret is inside or out. – Kylie Jun 24 '14 at 21:36
") < ta.selectionStart
– dandavis Jun 24 '14 at 22:49