Created
February 22, 2013 13:09
-
-
Save tborychowski/5013273 to your computer and use it in GitHub Desktop.
JS :: get and set caret position inside input box
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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