Skip to content

Instantly share code, notes, and snippets.

@jnicol
Last active Feb 25, 2019
Embed
What would you like to do?
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