How to Scroll to the End of a Long Text Input in All Browsers Except IE6-8 and Opera?

Susan Sarandon
Release: 2024-10-25 06:27:02
Original
516 people have browsed it

How to Scroll to the End of a Long Text Input in All Browsers Except IE6-8 and Opera?

Scrolling to the End of a Long Text Input

In this situation, where an image selector populates a text input field with an excessively long URL, viewing the beginning of the URL provides minimal information. A solution is sought to scroll the text field to the far right, displaying the end of the URL.

Browser Compatibility

The proposed solution utilizes HTMLInputElement.setSelectionRange() to set the cursor position at the end of the input value after explicitly setting the focus. This method is supported by all major browsers except IE6-8 and Opera.

Implementation

To implement this solution, follow these steps:

  1. Set the focus() of the input field to ensure it is active.
  2. Set the selection range of the input field using setSelectionRange(foo.value.length,foo.value.length). This will place the cursor at the end of the input value.

Example Code

<code class="javascript">var foo = document.getElementById("foo");
foo.value = "http://stackoverflow.com/questions/1962168/scroll-to-the-very-right-of-a-long-text-input";
foo.focus();
foo.setSelectionRange(foo.value.length,foo.value.length);</code>
Copy after login

Caveats

While this solution successfully scrolls the text field to the end of the URL, it comes with a minor caveat: once the input field loses focus, it will revert to displaying the beginning of the URL.

The above is the detailed content of How to Scroll to the End of a Long Text Input in All Browsers Except IE6-8 and Opera?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!