Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery dropdown menu, tab accessibility

Tags:

jquery

Fiddle here: http://jsfiddle.net/emJcx/1/

I have a drop down menu that is a simple show and hide on hover. I would like this dropdown menu to be accessible by using the tab keys as well. Using this code:

$("li.trigger a").focus(function(){ 
    $(this).parent().find('ul').show();
});

I have enabled the dropdown to show on the head link focus.

The blur gets a little more complex. I tried this:

$("li.trigger ul li:last-child a").blur(function(){ 
    $(this).parent().parent().hide();
});

But it only works with forward tabs, not back-tabs (shift-tabs).

I have also tried something like this:

$('li.trigger').has('a:focus').find('ul').toggle();

But naturally this does not work.

Any thoughts on how this could work.

Many thanks.

like image 715
superUntitled Avatar asked Dec 14 '11 17:12

superUntitled


1 Answers

I have this working for you: http://jsfiddle.net/emJcx/24/

It may not be the most optimal solution possible, but here is what I did:

  1. You were limiting your focus event to the class of trigger but one of your li tags did not have that class so I removed it for now. You might want to button this down a bit because at the moment it will run for every li on the page.
  2. I changed the code to hide all of the child ul tags prior to showing the one you are currently on. This way when you shift-tab back up to the parent menu items and move away from the parent of a given sub menu it will disappear.
  3. I removed your blur event because it would have caused an issue when shift-tabbing back off of the last item. The functionality remains the same because the additional hide actually takes care of this.

The new code is simply:

$("li a").focus(function(){
  $(this).parent().parent().find('ul').hide();
  $(this).parent().find('ul').show();
});
like image 105
David Brainer Avatar answered Nov 20 '22 13:11

David Brainer