Skip to content

Instantly share code, notes, and snippets.

@tborychowski
Created February 22, 2013 13:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tborychowski/5013273 to your computer and use it in GitHub Desktop.
Save tborychowski/5013273 to your computer and use it in GitHub Desktop.
JS :: get and set caret position inside input box
function getCaretPosition (ctrl) {
var caretPos = 0;
// IE
if (document.selection) {
ctrl.focus ();
var sel = document.selection.createRange();
sel.moveStart ('character', -ctrl.value.length);
caretPos = sel.text.length;
}
// Firefox
else if (ctrl.selectionStart || ctrl.selectionStart == '0'){
caretPos = ctrl.selectionStart;
}
return caretPos;
}
function setCaretPosition (ctrl, pos){
if(ctrl.setSelectionRange) {
ctrl.focus();
ctrl.setSelectionRange(pos,pos);
}
else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment