Saturday, 1 February 2014

How to get caret position in textarea?

With Firefox, Safari (and other Gecko based browsers) you can easily use textarea.selectionStart, but for IE that doesn't work, so you will have to do something like this:
function getCaret(node) {
if (node.selectionStart) {
return node.selectionStart;
} else if (!document.selection) {
return 0;
}

var c = "\001",
sel
= document.selection.createRange(),
dul
= sel.duplicate(),
len
= 0;

dul
.moveToElementText(node);
sel
.text = c;
len
= dul.text.indexOf(c);
sel
.moveStart('character',-1);
sel
.text = "";
return len;
}
(complete code here)
I also recommend you to check the jQuery FieldSelection Plugin, it allows you to do that and much more...
Edit: I actually re-implemented the above code:

function getCaret(el) { 
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el
.focus();

var r = document.selection.createRange();
if (r == null) {
return 0;
}

var re = el.createTextRange(),
rc
= re.duplicate();
re
.moveToBookmark(r.getBookmark());
rc
.setEndPoint('EndToStart', re);

return rc.text.length;
}
return 0;
}

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More