Skip to content

Instantly share code, notes, and snippets.

@jelmerdemaat
Last active November 19, 2025 08:53
Show Gist options
  • Select an option

  • Save jelmerdemaat/7f879f3856da9e20716546613cb135d0 to your computer and use it in GitHub Desktop.

Select an option

Save jelmerdemaat/7f879f3856da9e20716546613cb135d0 to your computer and use it in GitHub Desktop.
Simple focus trap script
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
@jelmerdemaat
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment