Skip to content

Instantly share code, notes, and snippets.

@AnatoliyLitinskiy
Created July 5, 2018 12:15
Show Gist options
  • Save AnatoliyLitinskiy/0e81165f4ad4345f35bf80de7fd7a4be to your computer and use it in GitHub Desktop.
Save AnatoliyLitinskiy/0e81165f4ad4345f35bf80de7fd7a4be to your computer and use it in GitHub Desktop.
caret posiiton
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