Skip to content

Instantly share code, notes, and snippets.

@jimmynotjim
Created October 8, 2014 20:57
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 jimmynotjim/7a52eaa48c01690c4194 to your computer and use it in GitHub Desktop.
Save jimmynotjim/7a52eaa48c01690c4194 to your computer and use it in GitHub Desktop.
Menu JS examples
// currently
$('button.toggleNav').on('click', function() {
$('.top-bar__dropdown').toggleClass('MenuIsOpen');
});
// better
// Ensures that you only open the menu adjacent to the button if there are more than one.
// Great for reusing the same code throughout for multiple dropdowns
$('.toggleNav').on('click', function() {
var $this = $(this);
var $menu = $this.siblings('.dropNav'); // Requires adding/renaming classname on ul
$menu.toggleClass('MenuIsOpen');
});
// best
// Ensures that you only open the menu adjacent to the button *and* if you click anywhere off-menu/button it will close the menu
// All the benefits of the previous version, but even better UX!!!
(function() {
var $trigger = $('.toggleNav');
var $navs = $('.dropNav');
$('body').on('click', function(e) {
var $target = $(e.target);
var isTrigger = $target.closest($trigger).length;
if ( isTrigger ) {
e.preventDefault();
var $thisNav = $target.siblings('.dropNav');
$thisNav.toggleClass('MenuIsOpen');
} else {
$navs.removeClass('MenuIsOpen');
}
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment