I'm trying to get the caret position in a text area. I've used a bunch of different methods, and most involve getting a range or grabbing the selectionStart of the element. For some reason, while it works somewhat, whenever I'm still typing new characters and haven't inserted any yet, it returns one less than it should.
for example: given the following input, with the caret as |:
| : 0
a| : 1
ab| : 1 <- weird!
abc| : 2 <- still weird
ab| : 2 <- back to normal
abc| : 2 <- back to weird
ad|bc : 2 <- normal
adbce| : 5 <- now normal
I don't think I'm sure when it even happens -- it seems to be one less if you've typed in some characters but haven't inserted into the middle of the string, after which it starts working again.
why does the second character not add to the caret position? has anyone else found this?
EDIT: It's running on the 'input' event:
// use a solution from stack that works with jquery:
(function ($, undefined) {
$.fn.getCursorPosition = function() {
var el = $(this).get(0);
var pos = 0;
if('selectionStart' in el) {
pos = el.selectionStart;
} else if('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
return pos;
}
})(jQuery);
$(window).load(function(){
// when editing the query box
$("#query_textarea").bind('input', function(){
window.status=$("#query_textarea").getCaretPosition();
// do some other stuff
}
}
and I'm running Chrome on Mac