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
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
This divs can only gain focus using tab navigation so detection is really simple:
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.
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
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?