optionally disable `getInitialFocusNode` on `firstTabbableNode`
See original GitHub issueIn some cases, especially in modals, it’s undesirable to autofocus the first tabbable node because the first tabbable node is a close button. That’s solvable by giving the modal container tabindex="-1"
and setting initialFocus
to a selector for that matches the modal container.
But what if that modal may have autofocusing children, like a text input in a registration form? And for some reason you can’t assign initialFocus
to that input? In that case, the initialFocus
option prevents the focus trap fallback behaviour of keeping an already focused element inside the focus trap contained focused.
a solution to this case would be adding a boolean option like autoFocusFirstTabbable
, defaulted to true
, that when set to false
would prevent the fallback behavior of autofocusing the first tabbable element. Essentially, this change would make possible explicit consumer autofocus behavior instead of allowing the focus trap to search for a tabbable element and focus it.
this would be the crux of the change
function getInitialFocusNode() {
var node;
if (getNodeForOption("initialFocus") !== null) {
node = getNodeForOption("initialFocus");
} else if (container.contains(doc.activeElement)) {
node = doc.activeElement;
} else {
// update
node =
(config.autofocusFirstTabbableNode ? state.firstTabbableNode : null) ||
getNodeForOption("fallbackFocus");
// end update
}
if (!node) {
throw new Error(
"Your focus-trap needs to have at least one focusable element"
);
}
return node;
}
Issue Analytics
- State:
- Created 3 years ago
- Reactions:6
- Comments:6 (5 by maintainers)
Top GitHub Comments
@defnotrobbie @stefcameron Alright, that PR is up! #440
@CamilleHbp Yes! Thank you. Fixed with #440