Get and set the caret / cursor position in a text field (textarea, input, etc.). Tested on a few modern browsers and works as advertised.
Get the caret position in el
.
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 || {}); |