javascriptinputfocusonblur

How do I keep an input focused even when I click a button outside it


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


Solution

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

    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>