Skip to content

Instantly share code, notes, and snippets.

@adamcbrewer
Last active December 23, 2015 19:59
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save adamcbrewer/6686292 to your computer and use it in GitHub Desktop.
JS: Get and set the position of a carat/cursor for an element.
function _getCarat(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}
function _setCarat(el, start, end) {
if (typeof start == 'string' && start === 'end') {
start = el.value.length;
}
end = end || start;
el.setSelectionRange(start, end);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment