0

I want to pop out a menu, and when the user click positions other than the menu, the menu will hide. Also, if the click is on some nodes who have click listeners, those handling functions will not be triggered. I can use a transparent mask layer to implement this, but is there any easier way (since I use jQuery)? I tried the :not selector

$(document).on('click',':not(.menu)',function(e){
$('.menu').hide();
});

But it seems just not working (also should I add a e.stopPropgation() here)?

1 Answer 1

2

I would write something like this:

$(document).on('click', function(e){
  if($(e.target).parents(".menu").length == 0)
     $('.menu').hide();
});
Sign up to request clarification or add additional context in comments.

3 Comments

Good suggestion. One more issue with this is that the menu is activated by a button. How can I organize the listeners so when pressing the button the menu could show? Now when I click the button, the menu won't show... ( I add a condition that $('.menu').css('display')!='none' in your if statement, but in console it shows the menu is already shown (display:block) when this listener is triggered so it is hidden again)
Well, if($(e.target).parents(".menu").length == 0 && $(e.target).parents(".trigger_btn").length == 0) could work... thanks again.
You are giving answers on your questions faster than me :) You're welcome.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.