Skip to content

Instantly share code, notes, and snippets.

@jnicol
Last active February 25, 2019 23:56
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 jnicol/9b9ad2d21f950baa7ed83af5f88781cb to your computer and use it in GitHub Desktop.
Save jnicol/9b9ad2d21f950baa7ed83af5f88781cb to your computer and use it in GitHub Desktop.
Open/close a dropdown menu on hover.
/**
* Open/close a dropdown menu on hover.
*
* The menu does not need to be a child or sibling of the button, but there should be no gap
* on screen between the bottom of the button and the top of the menu.
*
* The menu will remain open until the user's mouse leaves both the menu and button.
*
* Requires jQuery.
*/
$('.button').on('mouseenter', function() {
$('.menu').addClass('open');
});
$('.button, .menu').on('mouseleave', function(e) {
if ($(e.currentTarget).hasClass('button')) {
if (!($(e.relatedTarget).hasClass('menu') || $(e.relatedTarget).closest('.menu').length)) {
$('.menu').removeClass('open');
}
} else if ($(e.currentTarget).hasClass('menu')) {
if (!($(e.currentTarget).hasClass('button') || $(e.relatedTarget).parent().hasClass('button'))) {
$('.menu').removeClass('open');
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment