I've been working on a dropdown/popup menu, and I have it working great, with one exception; when you click on the link (or hit the enter key) to open the menu, focus is supposed to be set to the next element that can receive focus. So in this example, clicking on the "Menu 1" link, should expand the menu, and set focus on "test 1". But for some reason, it jumps to the last focusable element (test 3) instead:
<ul class="axxs-menu">
<li><a class="trigger">Menu 1</a>
<ul class="content">
<li><a href="#1">test 1</a></li>
<li><a href="#2">test 2</a></li>
<li><a href="#3">test 3</a></li>
</ul>
</li>
</ul>
Here is the relevant js:
jQuery.extend(jQuery.expr[':'], {
focusable: function(el, index, selector){
return $(el).is('a, button, :input, [tabindex]');
}
});
function openPopmenu(element) {
$(element).removeClass('trigger-inactive').addClass('trigger-active').attr("aria-expanded", "true").attr("aria-selected", "true");
$(element).next('.collapsed').removeClass('collapsed').addClass('expanded').show().attr("aria-hidden", "false");
$(element).next().find(':focusable').focus();
}
And here is a code pen:
http://codepen.io/tactics/pen/EZbGBY
Any help is much appreciated.
Example 1: In this example the form input text field gets the focus as page loads by using focus() method . Here the input element is selected by input keyword in JQuery selector. | Set focus on a form input text field on page load. This input box gets the focus as the page loads.
In order to make an prevent an element from taking focus ("non-focusable"), you need to use Javascript to watch for the focus and prevent the default interaction. In order to prevent an element from being tabbed to, use tabindex=-1 attribute. Adding tabindex=-1 will make any element focusable, even div elements.
The :focusable psuedo selector is only available with jquery-ui. If your only using jquery then replace '.find(':focusable') with the following:
.find('button, a, input, select, textarea, [tabindex]:not([tabindex="-1"])')
A little improvement for Drews answer, since input type hidden is not focusable and should be excluded. So replace ".find(':focusable')" with this:
.find('button, a, input:not([type="hidden"]), select, textarea, [tabindex]:not([tabindex="-1"])')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With