0

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');
        }
    }
});
chris45
  • 261
  • 1
  • 4
  • 14

2 Answers2

0
function onMenuClick(){
    $('#id-of-menu').collapse('hide');
}

Add this in your menu items:

onclick="onMenuClick()"
a.bjorkmann
  • 89
  • 2
  • 9
  • Thanks for the answer. Is this designed to collapse the menu when the user clicks anywhere on the page? – chris45 Aug 13 '19 at 11:34
  • You can add onMenuClick() on any event you want. But I would simply add them to the menu item links to get the efffect you want. – a.bjorkmann Aug 13 '19 at 12:51
  • I'd like the menu to close whenever the user clicks anywhere on the page when it is open, not just when they click on the menu items. – chris45 Aug 13 '19 at 13:39
-1

'mouseup' event is not present on mobile devices, try 'click'

peter46
  • 389
  • 4
  • 9
  • Just tried that: no luck. I replaced 'mouseup' verbatim with 'click'. – chris45 Aug 13 '19 at 11:12
  • perhaps something around detecting the target? do you have a working code for this, or can you setup a codesandbox or jsfiddle or something to help seeing the problem? – peter46 Aug 13 '19 at 14:09
  • Thanks for your help Peter. I'm about to comment with a solution I found. – chris45 Aug 13 '19 at 14:15