How do you set the cursor position in a text field using jQuery? I\'ve got a text field with content, and I want the users cursor to be positioned at a certain offset when
I had to get this working for contenteditable elements and jQuery and tought someone might want it ready to use:
$.fn.getCaret = function(n) {
var d = $(this)[0];
var s, r;
r = document.createRange();
r.selectNodeContents(d);
s = window.getSelection();
console.log('position: '+s.anchorOffset+' of '+s.anchorNode.textContent.length);
return s.anchorOffset;
};
$.fn.setCaret = function(n) {
var d = $(this)[0];
d.focus();
var r = document.createRange();
var s = window.getSelection();
r.setStart(d.childNodes[0], n);
r.collapse(true);
s.removeAllRanges();
s.addRange(r);
console.log('position: '+s.anchorOffset+' of '+s.anchorNode.textContent.length);
return this;
};
Usage $(selector).getCaret()
returns the number offset and $(selector).setCaret(num)
establishes the offeset and sets focus on element.
Also a small tip, if you run $(selector).setCaret(num)
from console it will return the console.log but you won't visualize the focus since it is established at the console window.
Bests ;D