Search code examples
javascripthtmlfocus

Detect focus enter direction coming from the browser toolbar


Update: A workaround can be having an empty div just before the first focusable element and one after the last focusable element, and redirect focus to the correct element. Not sure if there is a less hacky solution.

I need to detect if focus was restored as a result of using tab navigation while the user is in the browser toolbar.

Is there any native solution for this ?

Using a keydown listener to check if tab or shift was pressed only works as long as the focus doesn't leave the "document".

If the element is the first or last focusable element and tab navigation is used the focus will jump to the browser toolbar and the key down listener will not longer work to detect the focus direction.

For accessibility reasons I need to keep the default focus navigation behavior ( Focus jumping to browser toolbar )


Solution

  • Note: This is a very specific problem that I encounter while developing an interactive canvas application where there is only one real focusable element.

    A workaround to detect how the user is returning from the toolbar can be having an empty div just before the first focusable element and one after the last focusable element, and redirect focus to the correct element:

    Focusable redirect elements

        <div id="next_focus_redirect" tabindex="0"></div>
        <button class="first_focusable">First</button>
        ...
        <button class="last_focusable">Last</button>
        <div id="prev_focus_redirect" tabindex="0"></div>
    

    This divs can only gain focus using tab navigation so detection is really simple:

     // User returns to page from toolbar using Tab navigation
     next_focus_redirect.addEventListener("focus", () => {
      // Redirect focus to actual first focusable element
      first_focusable.focus()
     })
     // User returns to page from toolbar using Shift + Tab navigation
     prev_focus_redirect.addEventListener("focus", () => {
      // Redirect focus to the last focusable element
      last_focusable.focus()
     })
    

    After redirecting focus the empty divs are not longer needed and they should not longer have a focus behavior, otherwise the page will become a focus trap and the user not longer can return to browser toolbar using toolbar navigation.