Search code examples
javascriptgoogle-chromefocusoutline

Focus outline is invisible in Chrome when using a keydown handler to control focus


I have an <input type="text" />.

When I Shift+Tab from the textfield, I want to focus on an li > a. I can't rely on the native tabbing behavior in this case, because I have an anchor element in between the <input /> and the target <a /> that I don't want to give focus to.

Thus, I add a keydown listener that forces focus to the <a /> that I care about.

In Chrome however, when I focus on the <input /> and Shift+Tab from the <input />, focus goes to the last <a />, but the outline is invisible. If I do another Shift+Tab + Tab to land back onto B, I now see the outline.

document.getElementById("f").addEventListener("keydown", (e) => {
  if (e.key === "Tab" && e.shiftKey) {
      e.preventDefault();
      document.querySelector("#list1 > li:last-child > a").focus();
  }
});
<ul id="list1">
  <li><a href="#">A</a></li>
  <li><a href="#">B</a></li>
</ul>

<a href="#" />
<input id="f" />

If I remove the keydown handler and the anchor element in between the textfield and the target anchor that I want to focus, the focus outline is rendered correctly.

Is this a known Chrome bug, and are there any workarounds for this? (Using Chrome 74)


Solution

  • You can prevent the other anchor from gaining focus using the tabindex attribute. Here is an example:

    <ul id="list1">
      <li><a href="#">A</a></li>
      <li><a href="#">B</a></li>
    </ul>
    
    <a href="#" tabindex="-1"/>
    <input id="f" />

    This may not work in all browsers.