Reputation: 2727
If I have a jQuery .click() event firing for both "body" and a "div", how would I get it to only execute for the div and not the body when the div is clicked? Basically, I'm making my own context menu and I want clicking anywhere outside the element (in this case, "div.button") to close the menu.
Rudimentary example:
$("body").click(function(event){
if($("div.menu").is(":visible")){
$("div.menu").hide();
}
});
$("div.button").click(function(event){
$("div.menu").show();
});
As you can guess, the $("body").click() prevents/hides the menu from even showing.
A little guidance would be much appreciated. Thanks for reading!
Upvotes: 2
Views: 7537
Reputation: 21089
You want to use event.stopPropagation()
within the click element. So:
$( 'div.button' ).click(function( e ) {
e.stopPropagation();
$( 'div.menu' ).show();
});
Upvotes: 1
Reputation: 2134
http://api.jquery.com/event.stopPropagation/
event.stopPropagation()
Upvotes: 6
Reputation: 13756
You have to stop propagating event like this
$("div.button").click(function(event){
event.stopPropagation();
// do something
});
than only your button will be clicked
Upvotes: 5