Making Bootstrap Dropdowns More Accessible
It’s as easy as copy & paste
Dropdowns are a major part of any software interaction so it’s important to make them accessible to all users. It’s not only the right thing to do, it’s downright easy. Here’s what we’ll go over:
1 & 2. adding a couple aria-roles to help screen readers
3. setting focus on the first item in the list when the dropdown opens
4. setting focus back to the dropdown toggle when the dropdown closes
1. Add aria-haspopup=”true” to .dropdown-toggle
This lets screen readers know the button will open a menu.
2. Add aria-expanded=”false” to .dropdown-menu
This sets the initial state of the dropdown. We’ll use JavaScript to toggle it depending on the dropdown state.
3. On open, set focus to the first item and toggle aria-expanded
Use Bootstrap’s shown.bs.dropdown event to determine when a dropdown is toggled. The function parameter (event, in the example below) gives us the target dropdown. For focus, we’ll use a short timeout because Bootstrap tries to be smart and focus on the toggle. We’ll also set aria-expanded to true.
// On dropdown open
$(document).on('shown.bs.dropdown', function(event) {
var dropdown = $(event.target);
// Set aria-expanded to true
dropdown.find('.dropdown-menu').attr('aria-expanded', true);
// Set focus on the first link in the dropdown
setTimeout(function() {
dropdown.find('.dropdown-menu li:first-child a').focus();
}, 10);
});
4. On close, set focus back to the toggle
To prevent the browser from losing focus when a dropdown is closed, we’ll focus back on its toggle. We’ll also set aria-expanded to false.
// On dropdown close
$(document).on('hidden.bs.dropdown', function(event) {
var dropdown = $(event.target);
// Set aria-expanded to false
dropdown.find('.dropdown-menu').attr('aria-expanded', false);
// Set focus back to dropdown toggle
dropdown.find('.dropdown-toggle').focus();
});
That’s it! Here’s the complete fiddle:
http://jsfiddle.net/mariusc23/hts7F/