J
j_macaroni
I found this code to calculate the caret position in a textarea. In the
script getCaret below, I pass it the TextArea1 element.
It seems to work until you press a CR. In which case you get the wrong
result because of this line: "textEl.caretPos.move("character",1)==1 )
--i; "
So now if you have 3 lines and you are at line 0, column 0 it shows a
5. I believe the move() method skips over CR/LF but
"textEl.value.length+1;" includes the CR/LF.
I know it has to do with CR/LF. Can anyone suggest how to fix this?
Thanks.
<html>
<body>
<script language=javascript>
function getCaret (textEl) {
if (textEl.createTextRange) {
textEl.caretPos = document.selection.createRange().duplicate();
var i=textEl.value.length+1;
while ( textEl.caretPos.parentElement() == textEl
&& textEl.caretPos.move("character",1)==1 ) --i;
return (i==textEl.value.length+1?-1:i);
}
}
</script>
<input name=caretPos type=text />
<TEXTAREA name="TextArea1"
style="position:absolute;left:64px;top:112px;width:816px;height:209px;z-index:2"
rows=10 cols=79
id="TEXTAREA1"
ONSELECT="document.main.caretPos.value=getCaret(this);"
ONCLICK="document.main.caretPos.value=getCaret(this);"
ONKEYUP="document.main.caretPos.value=getCaret(this);" >
</TEXTAREA>
</body>
</html>
script getCaret below, I pass it the TextArea1 element.
It seems to work until you press a CR. In which case you get the wrong
result because of this line: "textEl.caretPos.move("character",1)==1 )
--i; "
So now if you have 3 lines and you are at line 0, column 0 it shows a
5. I believe the move() method skips over CR/LF but
"textEl.value.length+1;" includes the CR/LF.
I know it has to do with CR/LF. Can anyone suggest how to fix this?
Thanks.
<html>
<body>
<script language=javascript>
function getCaret (textEl) {
if (textEl.createTextRange) {
textEl.caretPos = document.selection.createRange().duplicate();
var i=textEl.value.length+1;
while ( textEl.caretPos.parentElement() == textEl
&& textEl.caretPos.move("character",1)==1 ) --i;
return (i==textEl.value.length+1?-1:i);
}
}
</script>
<input name=caretPos type=text />
<TEXTAREA name="TextArea1"
style="position:absolute;left:64px;top:112px;width:816px;height:209px;z-index:2"
rows=10 cols=79
id="TEXTAREA1"
ONSELECT="document.main.caretPos.value=getCaret(this);"
ONCLICK="document.main.caretPos.value=getCaret(this);"
ONKEYUP="document.main.caretPos.value=getCaret(this);" >
</TEXTAREA>
</body>
</html>