On desktop, clicking outside of my bootstrap nav menu closes it. However this behaviour does not work on mobile.
I've tried to edit some code from a codepen to reference the relevant classes on my website, to no avail.
Here is the code I've used:
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');
}
});
I'd hoped that clicking outside the menu would remove the 'show' class from the menu, thereby hiding it. In practice though, nothing happens.
SOLUTION
The answer provided here by Henrywright solved my problem (obviously after changing relevant class and id names).
This is the eventual 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');
}
}
});