The best way to do :not in jQuery?

dom, javascript, jquery, performance

Solution

The best way to do this is with bubbling capture, like this:

$(document).click(function() {
   //close menu
})

$("#the_menu").click(function(e) {
  e.stopPropagation();
});

How this works is every click bubbles (unless you stop it, usually by `return false;` or `event.stopPopagation()`), so whatever you click bubbles all the way up to DOM...if a click does that, we close the menu. If it came from inside the menu, we stop the bubble...so the click doesn't bubble up, triggering a close. This approach uses only 2 event handlers instead of 1 on everything but the menu, so very lightweight :)

Problem

I have a menu in jQuery when you click on a link it opens up, but I want it so when you click somewhere else, anywhere else that is not the menu, it becomes hidden. At the moment I'm binding a click event to ``` $(':not(#the_menu)') ``` But this seems like I'm binding a click event to the entire minus the menu, is there a more efficient way of doing something like this?

Original source