Home  >  Article  >  Web Front-end  >  A simple way to move focus to the last position in js

A simple way to move focus to the last position in js

高洛峰
高洛峰Original
2016-12-05 11:52:001453browse

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();


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn