Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
93
rated 0 times [  99] [ 6]  / answers: 1 / hits: 29199  / 15 Years ago, fri, december 25, 2009, 12:00:00

I have an image selector that allows to choose an image from a gallery, then fills in the URL into a <input type=text> field. The URLs can be awfully long, and always seeing the first half of the URL in the text field has very little informational value.



Does somebody know a way to scroll to the very right of the text field so that the end of the URL is visible instead of the beginning? Without resorting to a textarea.


More From » html

 Answers
130

All browsers except IE6-8/Opera


Set HTMLInputElement.setSelectionRange() to the length of the input value after explicitly setting the focus(). The disadvantage is that it scrolls back to start once blurred.




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

<input id=foo>  




All browsers except IE/Opera


If you don't care about IE in its entirety, then set Element.scrollLeft to Element.scrollWidth. The disadvantage is the less browser support.




var foo = document.getElementById(foo);
foo.value = http://stackoverflow.com/questions/1962168/scroll-to-the-very-right-of-a-long-text-input;
foo.scrollLeft = foo.scrollWidth;

<input id=foo>




All browsers


If you'd like to support every single browser, consider to trick it with the dir (direction) attribute which you set to rtl (right-to-left). The disadvantage is that it's a hack which really need to be taken into consideration when it's editable and/or you develop a direction sensitive website, but this works on all browsers and is great on readonly inputs.




var foo = document.getElementById(foo);
foo.value = http://stackoverflow.com/questions/1962168/scroll-to-the-very-right-of-a-long-text-input;

<input id=foo dir=rtl>  




[#97987] Tuesday, December 22, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
colby

Total Points: 311
Total Questions: 102
Total Answers: 102

Location: Taiwan
Member since Mon, Sep 6, 2021
3 Years ago
;