OK, I have a weird need. I'm not trying to trap focus inside of a specific div, I'm trying to prevent it from entering specific other ones. I have a script which changes the class on a div from "collapsed" to "expanded" on focus. When a div has the class of "expanded", I want people to be able to focus on elements inside of it, and tab outside of it into other areas of the page, but not into the divs which have the class of "collapsed". So here's a hypothetical sample:
<nav>
<a href="#one">One</a>
<a href="#two">One</a>
<a href="#three">One</a>
</nav>
<div id="one" tabindex="-1" class="collapsed">
Prevent focus on elements on this div or on elements inside it
<button>Button</button>
<div>
<div id="two" tabindex="-1" class="expanded">
Allow focus in this div and to focus outside of it
<button>Button</button>
<div>
<div id="three" tabindex="-1" class="collapsed">
Prevent focus on elements on this div or on elements inside it
<button>Button</button>
<div>
<p>When focus is set on div two, pressing tab key should go to the button inside it, and then to this link: <a href="#">test link</a></p>
How would I go about doing that?
This can be done by adding inert
attribute to your collapsed divs.
This attribute makes all inputs inside your element non-interactive, the browser ignore input events sent by the user, including focus-related events and events from assistive technologies. Reference here
Then you would need to add/remove this attribute in addition to setting expanded/collapsed class. For example:
<html>
<nav>
<a href="#one">One</a>
<a href="#two">One</a>
<a href="#three">One</a>
</nav>
<div id="one" tabindex="-1" class="collapsed" inert>
Prevent focus on elements on this div or on elements inside it
<button>Button</button>
</div>
<div id="two" tabindex="-1" class="expanded">
Allow focus in this div and to focus outside of it
<button>Button</button>
</div>
<div id="three" tabindex="-1" class="collapsed" inert>
Prevent focus on elements on this div or on elements inside it
<button>Button</button>
</div>
<p>When focus is set on div two, pressing tab key should go to the button inside it, and then to this link: <a href="#">test link</a></p>
</html>
Note: the divs in your hypothetical example were not closed properly.