Studying the structure of an element HTMLInputElement
I got to method setSelectionRange
, which makes the text selection between the positions defined by the parameters, ie input.setSelectionRange(0, 8)
will select the characters between positions 0 and 8 of the value of the input
element. However, I saw a behavior that at first seemed strange and I still did not find official sources to explain it.
Consider the example below: a text field and a button; both when the text field receives the focus and the button is pressed, the contents of the field should be selected between positions 0 and 8, in the case of "Anderson".
const input = document.querySelector("input");
const button = document.querySelector("button");
input.addEventListener("focus", function (event) {
this.setSelectionRange(0, 8);
});
button.addEventListener("click", function (event) {
input.setSelectionRange(0, 8);
});
<input type="text" value="Anderson Carlos Woss">
<button>Selecionar</button>
As you can see, content is selected correctly when the field receives focus, but when you press the button, nothing happens. This behavior has been verified in both Opera, Firefox and Chrome and, interestingly, works as expected in IE11 and Edge. No messages appear in console .
Is this behavior expected in this situation? If so, is there any official source explaining why this is so? If not, why did not it work in some browsers?