Skip to content

Instantly share code, notes, and snippets.

@mrtag23
Created July 7, 2020 17:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrtag23/6423234d10e6275c689087826a946306 to your computer and use it in GitHub Desktop.
Save mrtag23/6423234d10e6275c689087826a946306 to your computer and use it in GitHub Desktop.
function trapFocus(element, namespace) {
var focusableEls = element.querySelectorAll('a[href]:not([disabled]), button:not([disabled]), textarea:not([disabled]), input[type="text"]:not([disabled]), input[type="radio"]:not([disabled]), input[type="checkbox"]:not([disabled]), select:not([disabled])'),
firstFocusableEl = focusableEls[0];
lastFocusableEl = focusableEls[focusableEls.length - 1];
KEYCODE_TAB = 9;
element.addEventListener('keydown', function(e) {
var isTabPressed = (e.key === 'Tab' || e.keyCode === KEYCODE_TAB);
if (!isTabPressed) {
return;
}
if ( e.shiftKey ) /* shift + tab */ {
if (document.activeElement === firstFocusableEl) {
lastFocusableEl.focus();
e.preventDefault();
}
} else /* tab */ {
if (document.activeElement === lastFocusableEl) {
firstFocusableEl.focus();
e.preventDefault();
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment