I'm very new to React and Javascript, but hoping someone might be able to offer thoughts regarding how to reliably switch keyboard focus on a route change. In the following, selecting any of the menu items(green box is an example) on the LHS leads to a change in the main screen(orange box), but keyboard focus remains on the LHS after pressing Enter.
What I'm trying to achieve is that the keyboard focus switches to being the text highlighted(blue box), thus giving a better experience from a usability point of view. Having searched google, I believe to command to achieve this to be one of the following:
document.getElementById('content-container').focus();
document.getElementById('reviews-in-progress-title').focus();
with the stated Ids being those from the blue boxes in the debug tools. They represent the main screen and specific element, respectively however, neither achieves the desired effect.
What I am able to achieve is switching focus to the element highlighted in the red box using the following:
document.getElementById('sortable-column-manuscriptTitle').focus();
So, my question for the floor is: why is it that I'm able to switch focus to the red box, but not the blue one? It feels like this will be a pretty common (and solved/understood) problem, but I'm not currently able to crack it. Any input gratefully received.
Thanks, Phil
Some browsers won't allow the focus to be moved to an element if it's not an interactive element. In the blue box, you have an <h1>
, which is not natively focusable. In the red box, you have a <buton>
, which is focusable.
To get around it, add tabindex="-1"
to the <h1>
.
This will allow the focus to be moved to a non-interactive element via JS but won't allow the user to tab to it.
Now, having said that, in general you should not move the user's focus unless there's a really good reason for it. You mentioned you wanted to do it for a
"better experience from a usability point of view"
As a keyboard only user, I would find that a worse experience. If I'm a new user to the app and I wanted to explore the LHS menu to see what's available, I would tab to the menu, press enter or space to select the menu, then see what appears on the right. I'd then want to tab to the next menu item and select it to see what appears, but you moved my focus over to the right so now I have to shift+tab all the way back up to the menu. If I were using a sip-and-puff device or another assistive technology instead of a keyboard, that's going to be a lot of effort.
So your intention is good but it might cause a lot of difficulty for some users. That's why I recommend not moving the user's focus unless there's a really, really good reason for it.
Of course the opposite argument can be made. If the focus is not moved then the sip-and-puff user will have to navigate all the way over to the right side to interact with what appears.
You have to do some research to see what might benefit the most users without adversely affecting other users.