skip to Main Content

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 )

2

Answers


  1. Chosen as BEST ANSWER

    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.


  2. Detecting focus changes due to TAB or SHIFT + TAB navigation can be tricky, especially when dealing with browser toolbars. Here’s a potential solution using JavaScript:

    Capture keydown events: Listen for TAB and SHIFT + TAB keydown events.

    Check focus direction: Determine if the focus is moving forward (TAB) or backward (SHIFT + TAB).

    Handle focus changes: Implement logic to handle focus changes within your application.

    Here’s a sample code snippet to get you started:

    javascript

    document.addEventListener('keydown', (event) => {
        if (event.key === 'Tab' || event.key === 'Shift') {
            const currentElement = document.activeElement;
            const nextElement = document.querySelector(':focusable');
            const previousElement = document.querySelector(':focusable + :focusable');
    
            if (event.key === 'Tab' && nextElement) {
                // Focus moved forward
                console.log('Focus moved forward to:', nextElement);
            } else if (event.key === 'Tab' && previousElement) {
                // Focus moved backward
                console.log('Focus moved backward to:', previousElement);
            }
        }
    });
    
    // Helper function to select focusable elements
    function getFocusableElements() {
        return Array.from(document.querySelectorAll('a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])'));
    }
    

    This code listens for keydown events and checks if the focus is moving forward or backward based on the TAB key. You can customize the logic to handle focus changes as needed.

    Does this help with your requirements?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search