twitter/bootstrap — Issue #684: Keyboard navigation for dropdowns
Author: gabrielhurley
Created: 2011-11-23 21:17:17+00:00
State: open

The current JavaScript implementation of dropdowns doesn't support keyboard navigation. Adding some event handling for keyboard events would go a long way towards aiding in 508 compliance and making power-users happy.

I hacked out a quick set of code that works for my purposes, but don't have time to turn it into a polished pull request right now. Perhaps someone else can take it the final mile:

```
$('.dropdown').bind('keydown', function (evt) {
var $this = $(this);
switch(evt.keyCode) {
case 13: // Enter key
case 32: // Space bar
case 38: // Up arrow
case 40: // Down arrow
$this.addClass("open");
$this.find('.dropdown-menu a:first').focus();
break;
case 27: // Escape key
$this.removeClass("open");
}
});

$('.dropdown-menu a').bind('keydown', function (evt) {
var $this = $(this);

function select_previous () {
$this.parent('li').prev().find('a').focus();
evt.stopPropagation();
}

function select_next () {
$this.parent('li').next().find('a').focus();
evt.stopPropagation();
}

switch(evt.keyCode) {
case 13: // Enter key
case 32: // Space bar
$this.click();
$this.closest('.dropdown').removeClass('open');
evt.stopPropagation();
break;
case 9: // Tab key
if (evt.shiftKey) {
select_previous();
}
else {
select_next();
}
evt.preventDefault();
break;
case 38: // Up arrow
select_previous();
break;
case 40: // Down arrow
select_next();
break;
}
});
```