Skip to content

Instantly share code, notes, and snippets.

@andybroomfield
Created July 1, 2021 08:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andybroomfield/18b6201dc98554085f6bdc076540c5da to your computer and use it in GitHub Desktop.
Save andybroomfield/18b6201dc98554085f6bdc076540c5da to your computer and use it in GitHub Desktop.
BHCC Services mega menu tabbing order
/**
* Accessibility tabbing support for servies megamenu
*/
(function($) {
/**
* Check Key pressed is Tab Key
* @param {Event} e jQuery keypress event
* @return {Boolean}
*/
function isKeyTabKey(e) {
var keyCode = e.keyCode || e.which;
return keyCode === 9 ? true : false;
}
$(document).ready(function() {
// Services tab links
var servicesLink = $('#desktop-services-link');
var headerExpand = $('.header--expand').first();
var searchBoxInput = $('#site-search--desktop').find('input').first();
var firstHeaderExpandLink = headerExpand.find('a').first();
var lastHeaderExpandLink = headerExpand.find('a').last();
// set the services tabs to tabindex="-1" by default so skipped
headerExpand.find('a').attr('tabindex', '-1');
// when tabbing off the services menu, tab into the services links if it is open
servicesLink.keydown(function(e) {
if (headerExpand.is(':visible') && !e.shiftKey && isKeyTabKey(e)) {
e.preventDefault();
firstHeaderExpandLink.focus();
}
});
// when tabbing off the services last link, tab to the search box
lastHeaderExpandLink.keydown(function(e) {
if (!e.shiftKey && isKeyTabKey(e)) {
e.preventDefault();
searchBoxInput.focus();
}
});
// when shift tabbing off the services first link (reversing tab order), tab to the services menu
firstHeaderExpandLink.keydown(function(e) {
if (e.shiftKey && isKeyTabKey(e)) {
e.preventDefault();
servicesLink.focus();
}
});
// when shift tabbing off the search box (reversing tab order) go back to services tab if it is open
searchBoxInput.keydown(function(e) {
if (headerExpand.is(':visible') && e.shiftKey && isKeyTabKey(e)) {
e.preventDefault();
lastHeaderExpandLink.focus();
}
});
// when focused on a link in the services menu, set services links back into tab order
headerExpand.find('a').focus(function() {
headerExpand.find('a').attr('tabindex', '0');
});
// when focus removed from a link in the services menu, remove services links out of tab order
// @todo: only if another link in the services menu does not have focus
headerExpand.find('a').blur(function() {
headerExpand.find('a').attr('tabindex', '-1');
});
});
}) (jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment