Created
July 5, 2018 12:15
-
-
Save AnatoliyLitinskiy/0e81165f4ad4345f35bf80de7fd7a4be to your computer and use it in GitHub Desktop.
caret posiiton
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 (value) { | |
// Initialize | |
let iCaretPos = 0; | |
const field = document.activeElement; | |
// IE Support | |
if (document.selection) { | |
// To get cursor position, get empty selection range | |
const oSel = document.selection.createRange(); | |
// Move selection start to 0 position | |
oSel.moveStart('character', -value.length); | |
// The caret position is selection length | |
iCaretPos = oSel.text.length; | |
} | |
// Firefox support | |
else if (field.selectionStart || field.selectionStart === 0) | |
iCaretPos = field.selectionStart; | |
// Return results | |
return iCaretPos; | |
} | |
function setCaretPosition(caretPos) { | |
var elem = document.activeElement; | |
if(elem != null) { | |
if(elem.createTextRange) { | |
var range = elem.createTextRange(); | |
range.move('character', caretPos); | |
range.select(); | |
} | |
else { | |
if(elem.selectionStart) { | |
elem.setSelectionRange(caretPos, caretPos); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment