Reputation: 3544
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
Upvotes: 1
Views: 272
Reputation: 4304
I ran into the same issue when developing for an embedded device with an older webkit-based browser. It's an issue with the timing of dispatching the events and updating the control. In the event handler I check the length of the value of the field and the caret position and they're not the same, when typing in a field. The issue has been fixed in mid-2013 in webkit as far as I can tell. Ref: https://bugs.webkit.org/show_bug.cgi?id=110742
Edge, recent Safari, Firefox, Chrome all work as expected.
Upvotes: 0
Reputation: 1946
Does this answer your question?
pure JS: https://stackoverflow.com/a/1891501/671373
jQuery: https://stackoverflow.com/a/1909997/671373
Otherwise you might check "jQuery - fieldSelection"
https://github.com/localhost/jquery-fieldselection
From its description: "A jQuery plugin to get'n'set the caret/selection."
Upvotes: -1