mclibrary keyboard user dropdown menu support
The snippet can be accessed without any authentication.
Authored by
Joel Crawford-Smith
Add this CSS (or similar):
/* hide at small width */
.wcag21-toggle {
display: none;
}
/* show on wide width */
@media (min-width: 960px) {
.wcag21-toggle {
display: block;
position: relative;
margin-top: -33px;
font-size: 8px;
font-weight: bold;
padding: 7px;
float: right;
color: #fff;
}
}
And add the JS below:
menu-keyboard-support.js 1.86 KiB
/**
* mclibrary keyboard user dropdown menu support
*/
// Add toggle button
jQuery('#main-menu > li > a').after('<button aria-expanded="false" class="wcag21-toggle"><span aria-hidden="true">▽</span><span class="sr-only">Toggle sub menu</span></button>');
jQuery('.nav-dropdown').attr('tabindex','0').attr('aria-label','sub menu wrapper');
// Maintain aria-expanded attributes and show/hide sub menus
jQuery('.wcag21-toggle').bind('click', function (e) {
var expandedState = jQuery(this).attr('aria-expanded');
var id_of_sub = '#' + jQuery(this).parent().attr('class').split(" ").pop();
if (expandedState == 'true') {
jQuery(this).attr('aria-expanded', 'false');
jQuery(id_of_sub).css('display','none');
}
else {
jQuery(this).attr('aria-expanded', 'true');
jQuery(id_of_sub).css('display','block');
jQuery(id_of_sub).focus();
}
return false
});
// When sub menu has focus and user shift+tab backwards, send focus to it's triggering button
jQuery('.nav-dropdown').on('keydown', function(event) {
if (event.shiftKey && event.keyCode == 9) {
var this_subs_toggle_class = '.' + jQuery(this).attr('id');
jQuery(this_subs_toggle_class).find('> button.wcag21-toggle').focus();
}
return false
});
// Hide menu on escape key
document.addEventListener('keydown', function(event) {
if (event.key === "Escape") { // Escape key
jQuery('.wcag21-toggle').attr('aria-expanded', 'false');
jQuery(".nav-dropdown").css('display','none');
}
return false
});
// Maintain aria-expanded on hover
jQuery("#main-menu > li").bind('mouseenter', function () {
jQuery(this).find('> button').attr('aria-expanded', 'true');
return false
});
jQuery("#main-menu > li").bind('mouseleave', function () {
jQuery(this).find('> button').attr('aria-expanded', 'false');
return false
});
Please register or sign in to comment