Last active
November 19, 2025 08:53
-
-
Save jelmerdemaat/7f879f3856da9e20716546613cb135d0 to your computer and use it in GitHub Desktop.
Simple focus trap script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| containerElement.addEventListener('blur', (evt) => { | |
| const { target: previousFocusEl, relatedTarget: nextFocusEl, currentTarget: container } = evt; | |
| // Do nothing if the next focus remains inside our container: | |
| if (container.contains(nextFocusEl)) return; | |
| // Otherwise, stop exiting the container: | |
| evt.preventDefault(); | |
| // Find all focusables (adjust to your own liking) and filter out `display: none` elements: | |
| const focusables = [...container.querySelectorAll('button, a[href], input, select, textarea, [tabindex]:not([tabindex^="-"])')].filter(el => el.offsetParent); | |
| // We want either the first or the last one, depending on the previous one: | |
| const newFocus = previousFocusEl == focusables[0] ? focusables.pop() : focusables.shift(); | |
| newFocus.focus(); | |
| }, true) // Capture child events |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example:
https://codepen.io/jelmerdemaat/pen/xbVrodm