Let's say I have an input
<input type="text" id="inPut" autofocus>
and a button
<button id="btn">Some text</button>
I want that onblur, it loses focus (as it normally would), but when I click this button, nothing happens to the focus i.e it does not lose focus
Let's say I have an input
<input type="text" id="inPut" autofocus>
and a button
<button id="btn">Some text</button>
I want that onblur, it loses focus (as it normally would), but when I click this button, nothing happens to the focus i.e it does not lose focus
Share Improve this question asked Apr 24, 2021 at 16:16 Emeka OrjiEmeka Orji 3065 silver badges14 bronze badges 2- If the button is clicked when the input does not have focus should the input gain focus? – Ben Stephens Commented Apr 24, 2021 at 16:25
- @BenStephens No it should not – Emeka Orji Commented Apr 24, 2021 at 18:04
1 Answer
Reset to default 7You can use JS to focus the input on button click.
const btn = document.querySelector("#btn");
const inp = document.querySelector("#inp");
btn.addEventListener("click", () => {
inp.focus();
});
<input id="inp" type="text">
<button id="btn">Click</button>
If you don't want the input to focus on click if it is not already focused.
To achieve this we cannot simply do:
btn.addEventListener("click", () => {
if (inp === document.activeElement) {
inp.focus();
}
});
Because the condition inp === document.activeElement
would never be true, as clicking on the button would make the button the active element.
We can use the mouseover
event and store the input's
focus" information in a variable and this would not suffer from the same problem as before because mouseover
would fire before the button gets focused.
And then inside the click
listener we will focus the input if it was already focused.
const btn = document.querySelector("#btn");
const inp = document.querySelector("#inp");
let isInputFocused = false;
btn.addEventListener("mouseover", () => {
if (inp === document.activeElement) {
isInputFocused = true;
} else {
isInputFocused = false;
}
});
btn.addEventListener("click", () => {
if (isInputFocused) {
inp.focus()
}
});
<input id="inp" type="text">
<button id="btn">Click</button>