When using my bootstrap nav menu on desktop, it closes when clicking outside of it. However, this feature doesn't work on mobile devices.
I attempted to modify some code from a codepen to match the classes on my website, but it didn't work.
Below is the code I tried:
const $menu = $('#id-of-menu');
$(document).mouseup(e => {
if (!$menu.is(e.target) // if the target of the click isn't the container...
&& $menu.has(e.target).length === 0) // ... nor a descendant of the container
{
$menu.removeClass('show');
}
});
My goal was for clicking outside the menu to hide it by removing the 'show' class, but it didn't work as expected.
SOLUTION
I found a solution to my issue here, provided by Henrywright (after adjusting class and id names).
Here is the modified code I used:
jQuery('body').bind('click', function(e) {
if(jQuery(e.target).closest('.navbar').length == 0) {
// click happened outside of .navbar, so hide
var opened = jQuery('#id-of-menu').hasClass('show');
if ( opened === true ) {
jQuery('#id-of-menu').collapse('hide');
}
}
});