valerio0999 valerio0999 - 6 months ago 11
jQuery Question

jquery .not() for closing menu (or modal) not working

I have a menu that toggles open clicking on a button. I was asked to make it close whenever you click outside of the open menu as well.

This is practically identical to the "click outside of a modal to close it" behaviour, but applied on a fixed menu header.

I thought of something like this:

$('*').not('.header').on('click', function(){
//close menu function
console.log("close the menu")
});


but it's not working in many ways:

1) wherever i click, the console.log fires
2) for each click, i get 3 console.log fired.

Here is a fiddle: https://jsfiddle.net/Ln1wabqq/1/

I've tried changing the
$('*')
to


  • $('*:not(".header")')

  • $('*').not('.header, .header *')

  • $('').not('.header')



but I get the same exact output. Am I on a totally wrong path here?

thanks a lot for your help

Answer

You could detect a click outside element like this :

$(document).click(function(event) { 
    if(!$(event.target).closest('.header').length){
        // click outside .header
    }
});