Skip to content

Instantly share code, notes, and snippets.

@IngoWinter
Created March 24, 2023 13:13
Show Gist options
  • Save IngoWinter/7e9057c23da38daa56ac42eef960a916 to your computer and use it in GitHub Desktop.
Save IngoWinter/7e9057c23da38daa56ac42eef960a916 to your computer and use it in GitHub Desktop.
Focus Trapping BITV
function trapFocus(element) {
'use strict';
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])');
var firstFocusableEl = focusableEls[0];
var lastFocusableEl = focusableEls[focusableEls.length - 1];
var 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();
}
}
});
}
$('#header__offscreenToggler').on('click', function (e) {
e.preventDefault();
e.stopImmediatePropagation();
openOffscreenWrapper();
// keyboard
if (e.detail === 0) {
$('#offscreen__offscreenToggler').focus();
trapFocus(document.getElementById('offscreen__wrapper'));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment