JS Trap focus

containerElement = document.getElementById('id');

focusableElements = [
    ...containerElement.querySelectorAll('a[href], button, input, textarea, select, details, [tabindex]:not([tabindex="-1"])')
  ].filter(
    el => (el.offsetParent != null) && el => !el.hasAttribute('disabled') && !el.getAttribute('aria-hidden')
);

firstFocusableEl = focusableElements[0];
lastFocusableEl = focusableElements[focusableElements.length - 1];

lastFocusableEl.addEventListener('keydown', function(event) {
  if (event.shiftKey === false && event.key === 'Tab') {
    event.preventDefault();
    firstFocusableEl.focus();
  }
});

firstFocusableEl.addEventListener('keydown', function(event) {
  if (event.shiftKey === true && event.key === 'Tab') {
    event.preventDefault();
    lastFocusableEl.focus();
  }
});

Leave a Reply

Your email address will not be published. Required fields are marked *

89 − 80 =

This site uses Akismet to reduce spam. Learn how your comment data is processed.