photondesign
asked on
Caret Position in Textarea using IE8 and Javascript
I need to find the current caret (cursor) position in a textarea in Internet Explorer 8. The attached code works in firefox, but not in IE8. It has provision for IE but I think it only works in IE7, there is a problem with the createRange in IE8 when nothing is actually selected.
I need the position of the caret, relative to the start of the text in the textarea, the content may include new lines, etc.
I need the position of the caret, relative to the start of the text in the textarea, the content may include new lines, etc.
// Function used to get caret's position
getCaretPosition = function(oField)
{
// Initialize
var iCaretPos = 0;
// IE Support
if (document.selection)
{
oField.focus ();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange();
// Move selection start to 0th position
oSel.moveStart("character", 0 - oField.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == "0")
{
iCaretPos = oField.selectionStart;
}
// Return results
return (iCaretPos);
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
You're welcome!
ASKER
I used bits of that code rather than using the actual module. As it was an modification to the jquery autocorrect module that I was creating. Now all works great. Thanks.
Thanks for the points!
ASKER