The Easiest Way to Trap Focus

The Easiest Way to Trap Focus

·

1 min read

Ever need to trap the focus of the browser to a modal, a tour guide, or something else while trying to balance accessibility?

I am far from an expert, but one thing I found on StackOverflow that helped me was this snippet from Shane McCurdy from this StackOverflow discussion:

<span
  tabindex="0"
  aria-hidden="true"
  style="opacity: 0"
  onfocus="document.getElementById('element_id').focus()"
></span>

Add this to the end of the desired focused content.

It collects the next "tab" entry and loops back up to the first item in your desired focusable content via its id.

You could also go the Vue route with refs and events!

I am not an accessibility expert, but this appears to be valid! Please let me know if I am missing something.

Thanks Shane! Saved me a ton of effort!