Skip to content

Instantly share code, notes, and snippets.

@akprasad
Last active December 19, 2015 20:59
Show Gist options
  • Save akprasad/6017236 to your computer and use it in GitHub Desktop.
Save akprasad/6017236 to your computer and use it in GitHub Desktop.
Get and set caret / cursor position in any text field (input, textarea, etc.)

caret.js

Get and set the caret / cursor position in a text field (textarea, input, etc.). Tested on a few modern browsers and works as advertised.

namespace.getCaretPosition(el)

Get the caret position in el.

namespace.setCaretPosition(el, pos)

Set the caret position in el to position pos.

(function(ns) {
$.fn.getCaretPosition = function() {
return ns.getCaretPosition($(this).get(0));
}
$.fn.setCaretPosition = function() {
return ns.getCaretPosition($(this).get(0));
}
})(window.namespace = window.namespace || {});
(function(ns) {
ns.getCaretPosition = function(el) {
// Normal browsers
if (el.selectionStart !== undefined) {
return el.selectionStart;
}
// IE
else if (document.selection) {
el.focus();
var range = document.selection.createRange();
range.moveStart('character', -el.value.length);
return range.text.length;
}
else {
console.log('getCaretPosition: no support for browser');
}
return -1;
}
ns.setCaretPosition = function(el, pos) {
// Normal browsers
if (el.setSelectionRange !== undefined) {
el.focus();
el.setSelectionRange(pos, pos);
}
// IE
else if (el.createTextRange) {
var range = el.createTextRange();
range.move('character', pos);
range.select();
}
else {
console.log('setCaretPosition: no support for browser');
}
}
})(window.namespace = window.namespace || {});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment