Last active
February 24, 2020 21:05
-
-
Save snowman-repos/3990793 to your computer and use it in GitHub Desktop.
JavaScript: Move cursor to the end of text input
This file contains hidden or 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 moveCursorToEnd(el) { | |
if (typeof el.selectionStart == "number") { | |
el.selectionStart = el.selectionEnd = el.value.length; | |
} else if (typeof el.createTextRange != "undefined") { | |
el.focus(); | |
var range = el.createTextRange(); | |
range.collapse(false); | |
range.select(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In older versions of Chrome, even reading
el.selectionStart
will cause a DOMException to be thrown if the element is an<input type="email">
. You need to wrap this in a try/catch block for it to actually be safe.