最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I keep an input focused even when I click a button outside it - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 7

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>

发布评论

评论列表(0)

  1. 暂无评论