daveycroqet
daveycroqet

Reputation: 2727

Having a jQuery .click() event only fire once when inside another .click() event

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

Answers (3)

Trevor Norris
Trevor Norris

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

Brandt Solovij
Brandt Solovij

Reputation: 2134

http://api.jquery.com/event.stopPropagation/

event.stopPropagation()

Upvotes: 6

Senad Meškin
Senad Meškin

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

Related Questions