Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best way to do :not in jQuery?

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?

like image 245
MintDeparture Avatar asked Apr 27 '10 11:04

MintDeparture


1 Answers

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 :)

like image 128
Nick Craver Avatar answered Oct 03 '22 20:10

Nick Craver