Created
July 7, 2020 17:34
-
-
Save mrtag23/6423234d10e6275c689087826a946306 to your computer and use it in GitHub Desktop.
This file contains 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
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