1

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

Emeka Orji
  • 174
  • 4
  • 11

1 Answers1

4

You 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.

You can store input's focus information in a variable, toggle that variable on button's mouseover event (this would work because mouseover fires before click and mouseover doesn't make the button active)

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>
Som Shekhar Mukherjee
  • 4,701
  • 1
  • 12
  • 28
  • @EmekaOrji Please check if this solves your problem, do let me know if you have any issues. – Som Shekhar Mukherjee Apr 24 '21 at 16:40
  • 3
    I was thinking that this second example wouldn't work on my phone because I wasn't expecting the mouseover event to fire just from a click, but it appears to work for me. If anyone finds that this doesn't work on a touch device, then possibly mousedown or pointerdown (or both) events could be used instead of mouseover (ref: https://stackoverflow.com/questions/7329141/how-do-i-get-the-previously-focused-element-in-javascript ). – Ben Stephens Apr 24 '21 at 17:05
  • 1
    Thanks @SomShekharMukherjee I will get back to you (here) as soon as I try it out – Emeka Orji Apr 24 '21 at 18:07
  • It was so helpful, I'm still trying to figure out how it worked, but it did!! Thanks @SomShekharMukherjee – Emeka Orji Apr 24 '21 at 19:20