Skip to content

Instantly share code, notes, and snippets.

@kmwalsh
Last active July 8, 2022 20:14
Show Gist options
  • Save kmwalsh/fb25c300051697d0fcef3a3aef952018 to your computer and use it in GitHub Desktop.
Save kmwalsh/fb25c300051697d0fcef3a3aef952018 to your computer and use it in GitHub Desktop.
// fix for keyboard focus states on scroll position or timed based popup implementations
//
// forces the focus back to the element that was focused prior to popup open
// fixes focus bug when faking a click on existing element to bring up a modal window
// fixes accessibility issue where the user's focus was changed when the popup shows
//
/**
* Gets keyboard-focusable elements within a specified element
* @param {HTMLElement} [element=document] element
* @returns {Array}
*/
function getKeyboardFocusableElements () {
return document.querySelectorAll(
'a, button, input, textarea, select, details,[tabindex]:not([tabindex="-1"])'
);
}
// implementation below fires on bootstrap modal close event -- change bootstrap event out for whatever event your modal fires on close
$('#modal').on('hidden.bs.modal', function () {
// catches an empty focus element (e.g., user hasn't interacted with page via keyboard yet)
if ( prePopupFocusedElement === document.body ) {
document.body.tabIndex = 0;
document.body.focus({preventScroll: true});
} else {
prePopupFocusedElement.focus();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment