Skip to content

Instantly share code, notes, and snippets.

@snowman-repos
Last active February 24, 2020 21:05
Show Gist options
  • Save snowman-repos/3990793 to your computer and use it in GitHub Desktop.
Save snowman-repos/3990793 to your computer and use it in GitHub Desktop.
JavaScript: Move cursor to the end of text input
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();
}
}
@alexf101
Copy link

alexf101 commented Feb 12, 2018

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment