JQuery: handling background / container click

I have a large div and a small button inside the div.

When clicking on a div, I want it to do something.
When the button is clicked, I want it to do something else.

$('#myDiv').click(OnDivClicked);
$('#myButton').click(OnButtonClicked);

      

Currently, when a button is clicked, both OnDivClicked and OnButtonClicked are fired.

How do you prevent OnDivClicked from being enabled on button click?

Thanks in advance.

+2


a source to share


1 answer


You need to prevent the bubble from being pressed with event.stopPropagation()

, for example:

$('#myButton').click(function(e) {
  OnButtonClicked();
  e.stopPropagation();
});

      



By default, many events bubble up to their parents all the way down to the DOM root, causing their event handlers for the same event type to fire ... to stop this you just need to stop the bubble behavior like the code above does. If you don't need the default action, return false;

will do that as well.

The difference between e.StopPopagation()

and return false;

would be more important if saying the anchor, stopping only the bubble, would not light up the parent handler click

, but would follow the link, whereas neitherreturn false

would .

+5


a source







All Articles