I've built a set of dropdown menus in CSS and jQuery, but I'm struggling to allow closing any open menus by clicking outside/on the body. I've found existing similar questions that suggest using the .closest()
method, but I can't seem to get this working:
$('body').click(function(e) {
if ($(e.target).closest('.dropdown-menu').length === 0) {
$('.dropdown-menu').hide();
}
});
I've also tried the following:
$('body').on('click', function() {
if ($('.dropdown-menu').is(':visible')) {
$('.dropdown-menu').hide();
}
});
Thanks!