Home > Article > Web Front-end > A simple way to move focus to the last position in js
When the input box (input/textarea) gets focus, move the focus to the end. In some cases, the user experience is good. Most of the methods on the Internet are for IE browser.
The code is as follows:
var el = document.getElementById('txtArticle'); var range = el.createTextRange(); range.moveStart('character', el.value.length); range.collapse(false); range.select();
In fact, you can delete the moveStart line, because after the createTextRange method creates the range, you can use the collapse method and the parameter is false to move to the end. collapse(true) moves the cursor to the beginning of the range, collapse(false) moves the cursor to the end of the range. Standard browsers such as Firefox can use w3c's setSelectionRange method.
The code is as follows:
var range, el = document.getElementById('txtPhone'); if (el.setSelectionRange) { el.focus(); el.setSelectionRange(el.value.length, el.value.length) } else { range = el.createTextRange(); range.collapse(false); range.select(); }
Note that the setSelectionRange method only applies to input/textarea elements. The focus of other non-native editable elements can be moved to the collapse method of the selection object,
For example:
var sel, el = document.getElementById('hint'); sel = window.getSelection(); sel.collapse(el, 1); el.focus();