I have an off-canvas-menu (#mobile-menu
) that opens when a button/trigger (.mobile-menu-toggle
) is clicked or pressed etc.
The menu opens fine on keyboard press, but it does not focus within the menu, instead the focus is on the next element in the document flow - the menu actually comes before the "trigger" in the document.
So I'm looking for a way to set the focus within the off-canvas-menu when it opens.
I have tried many variations of this, but nothing happens, the focus is still going to the next element instead of what I've specified:
$(document).on("keyup",".mobile-menu-toggle",function(e) {
if (e.which == 13) {
$("#mobile-menu ul").focus();
}
});
And here's a simplified version of the html:
<nav id="mobile-menu" aria-label="Main Mobile Navigation">
<div class="content">
<a href="#" aria-label="Mobile Homepage Link">... LOGO IMG ...</a>
<span class="heading">Navigation</span>
<ul class="page-navigation">
... NAV LINKS ...
</ul>
</div>
</nav>
<div id="mobile-nav-trigger">
<button class="mobile-menu-toggle" aria-label="Open Menu"></button>
</div>
I've also found if I try to add tabindex anywhere within the mobile-menu, the trigger no longer opens it on keypress.
How can I make it so that when the trigger opens the menu, the focus is inside of the #mobile-menu element?
After trying the solution found here: stackoverflow.com/a/15338848/1783695, that gave me some ideas... This solution worked, but it was also putting the focus on with a mouse click, where I just wanted the focus on keyboard press.
So I ended up with this, and it's working exactly how I needed:
Note: I added the class "focusable" and tabindex to the "Navigation" heading (we have more than one "heading" element) so it can focus there: