Last active
December 23, 2015 19:59
-
-
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.
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 _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; | |
} |
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 _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