Skip to content
Advertisement

Focus trap for multiple modals

I’m working on a trap focus modal functionality and it works well with a single element, but I can’t get it working with multiple elements. It traps focus only on last modal. I know there is something wrong with my loop, I tried to catch activeElement and add a condition if it’s equal to focused element but with no result.

Here is the CodePen example

HTML

JavaScript

JavaScript

JavaScript

Advertisement

Answer

You made a minor mistake with your loop in mobileAccessibility function.

When you loop through the modals in the section if ( body.classList.contains( 'showing-search-modal' ) ) { you close the loop too early.

This means you are setting firstEl = input; as the last modal no matter what (as you are overriding it) and same for lastEl = close;

By simply moving the loop to include the tabkey checks it works as expected.

A few other considerations

Now there are loads of things that you still need to consider from an accessibility perspective.

Things like the fact that screen reader users navigate by headings, sections, links etc. so just capturing Tab is not sufficient.

For example: you need to sit the modals outside of the <main> and then use aria-hidden="true" on the <main> element when the modals are open to hide everything else from screen readers.

Oh and add aria-modal to your modal, see this answer I gave to understand why.

Fixed code

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement