I have a big div, and a small button inside the div.
When the div is clicked, 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 the button is clicked, both OnDivClicked and OnButtonClicked are fired.
How do you prevent OnDivClicked getting fired when the button is clicked?
Thanks in advance.
You need to prevent the click from bubbling up using
event.stopPropagation(), like this:By default many event bubble up to their parents all the way to DOM root, causing their event handlers for the same event type to fire…to stop this you just need to stop the bubbling behavior like the code above does. If you don’t need the default action to occur,
return false;will also accomplish this.The difference between
e.StopPopagation()andreturn false;would be more important in say an anchor, stopping the bubble only would not fire the parent’sclickhandler but would follow the link, whereasreturn falsewould do neither.