valerio0999 valerio0999 - 2 years ago 74
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:

I've tried changing the

  • $('*: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 Source

You could detect a click outside element like this :

$(document).click(function(event) { 
        // click outside .header
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download