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
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With