Reputation: 43
Problem:
When text selection is set programmatically using setSelectionRange
(in an input field narrower than the content) , the desired part is selected but the selection isn't scrolled into visibility. Seems to be occurring on chrome and opera. Works for Firefox and edge.
State: It's actually a known issue since 2014 according to the chromium bug report. So i am mainly interested in a workaround because this issue causes some other weird side effect in my application.
I already tried timeouts, additional focus-blur pairs.
minimal case with the following input:
<input id="text" type="text" value="123456789" size="2"/>
and the following function:
function selectText() {
var input= document.getElementById("text");
input.focus();
setTimeout(function(){ //workaround for edge
input.setSelectionRange(7,9,"forward");
}, 1);
}
Here's the code to try out.
Upvotes: 2
Views: 169
Reputation: 6747
Combining a few different techniques, such as using .focus()
and setting .scrollLeft
to scrollWidth
, you can relatively easily deal with this problem. Code sample below (based on the Fiddle provided), as well as in this Fiddle. Let me know if this works as expected in all browsers (only tested for Chrome).
function selectText() {
var input = document.getElementById("text");
input.focus();
var txt = input.value;
setTimeout(function() {
document.getElementById("text").focus();
document.getElementById("text").scrollLeft = document.getElementById("text").scrollWidth;
document.getElementById("text").setSelectionRange(7, 9, "forward");
document.getElementById("selection").innerHTML = "selection is: " + txt.substring(input.selectionStart, input.selectionEnd);
}, 1);
}
<p id="selection"></p>
<input id="text" type="text" value="123456789" size="2" />
<input type="button" value="Select" id="select" onclick="selectText()">
Upvotes: 1