Create a gist now

Instantly share code, notes, and snippets.

Embed
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