Skip to content

Instantly share code, notes, and snippets.

@adamcbrewer adamcbrewer/getCarat.js
Last active Dec 23, 2015

What would you like to do?
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) {
var r = document.selection.createRange();
if (r == null) {
return 0;
var re = el.createTextRange(),
rc = re.duplicate();
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
You can’t perform that action at this time.