Jolen
Jolen

Reputation: 121

jQuery close menu auto closing

Building a mobile menu and would like when the user clicks on the document, not the menu to close the menu if its open. Problem is that when the first click is fired to open the mobile it automatically closes. I'm struggling to get this bit to work.

The code recognises the click so the window is detecting the right action. I'm just missing one final step I think.

Code is:

$('.mobile-menu-button').click(function(e) {
    e.preventDefault();
    $('.mobile-menu').slideToggle('slow');
});
// close on off click
$(window).click(function(e){
    e.preventDefault();
    e.stopPropagation();
    if($('.mobile-menu').css("display") == 'block') {
        $('.mobile-menu').slideToggle();
        console.log('click');
    }
});

Thanks

Upvotes: 0

Views: 399

Answers (1)

Francesco
Francesco

Reputation: 1413

You can use event delegation. When you click on '.mobile-menu', you open it or close it, when you click somewhere else you only close it.

$(window).on('click', function(e){
    e.preventDefault();
    if ($(e.target).hasClass('mobile-menu-button')) {
      $('.mobile-menu').slideToggle('slow');
    } else {
      $('.mobile-menu').css('display') === 'block' && $('.mobile-menu').slideUp();
    }
});

a basic example on this fiddle: https://jsfiddle.net/6e7atrmn/2/

Upvotes: 1

Related Questions