How to focus at the end of the text in an input field using Javascript.
I want to move the mouse over the input field to focus on it, and the curse is at the end of the text.
I just use the Event as the following, the curse is at the first.
document.addEventListener('mouseover', function (e) {
if (e.target.localName ==='input'){
e.target.focus();
}
});
document.addEventListener('mouseout', function (e) {
e.target.blur();
});
A safer solution where you don't modify the contents/value of the input field is by triggering the selection of the value.
document.addEventListener('mouseover', function (e) {
let elm = e.target;
if (elm.localName ==='input'){
elm.focus();
elm.selectionStart = elm.value.length;
elm.selectionEnd = elm.value.length;
}
});
document.addEventListener('mouseout', function (e) {
e.target.blur();
});
<input value="hello"/>