Skip to content

Instantly share code, notes, and snippets.

@zArubaru
Last active November 11, 2019 13:32
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 zArubaru/b2bf7885ce17be88483e0c0da08deefc to your computer and use it in GitHub Desktop.
Save zArubaru/b2bf7885ce17be88483e0c0da08deefc to your computer and use it in GitHub Desktop.
Basic mobile menu functionality with tab cycle locking
import $ from 'jquery';
export default function() {
const $body = $('body');
const $hamburger = $('.js-header-hamburger');
const $mobileMenu = $('.js-mobile-menu');
const $lastMenuItem = $mobileMenu.find('a').last();
const $close = $('.js-mobile-menu-close');
const $content = $('.js-mobile-menu-content');
$hamburger.click(() => {
$body.addClass('has-mobile-menu'); // body -> overflow: hidden;
setTimeout(() => {
$content.addClass('is-visible');
$close.focus();
}, 0);
});
$close.click(() => {
$body.removeClass('has-mobile-menu');
$content.removeClass('is-visible');
$hamburger.focus();
});
$mobileMenu.on('keydown', 'a, button', function lockTabCycle({
which,
shiftKey,
}) {
if (which !== 9) {
return true;
}
const $this = $(this);
if (shiftKey && $this.is($close)) {
$lastMenuItem.focus();
return false;
}
if (!shiftKey && $this.is($lastMenuItem)) {
$close.focus();
return false;
}
return true;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment