A Simple Method for moving js focus to the last position

Source: Internet
Author: User
A simple method to move the focus of js to the last position. When the input box (input/textarea) gets the focus, it moves the focus to the end. In some cases, the user experience is good. Most of the methods on the Internet are for IE browsers.

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 a range, you can use the collapse method. If the parameter is false, you can move it to the end. Collapse (true) moves the cursor to the beginning of range, and collapse (false) moves the cursor to the end of range. Firefox and other standard browsers can use the w3c 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 applies only to input/textarea elements. You can use the collapse method of the selection object to move the focus of other native editable elements,

For example:

var sel, el = document.getElementById('hint');sel = window.getSelection();sel.collapse(el, 1);el.focus();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.