-
Notifications
You must be signed in to change notification settings - Fork 0
focusTrap
Mike Byrne edited this page Mar 14, 2023
·
3 revisions
Traps keyboard tabbing focus within a node; so if you open a modal and you want the users tab focus to stay within that modal. Helps accessibility as users won't be able to tab focus outside of the active element.
3.1.0
brings an updated backwards compatible version.
From 3.1.0
if the content of your focus trap changes, the focus trapping updates. For example - lets say on initial load the last focusable item is a specific button and because of user interaction and now a new button is the last focusable item - then focus trap will automatically adapt.
From 3.1.0
also handles cases where the focus escapes the focus trap better than earlier versions.
- setFocusOnTarget (handled automatically)
- getFocusableElements (from
3.1.0
- handled automatically)
- none
- nothing
Setup:
import { focusTrap } from './functions'
document.addEventListener('DOMContentLoaded', function(){
// listen for focus trap requests
focusTrap();
});
To trap focus, where element
is the node you want to trap focus within:
triggerCustomEvent(document, 'focus:trap', {
el: modalNode,
});
// focus is now trapped inside the `modalNode`
To un-trap focus:
triggerCustomEvent(document, 'focus:untrap');
// focus is now released