I have an element that contains many components within it. Lets call this element box. Now inside the box I have many different elements, pictures, text and buttons.
Example: http://jsfiddle.net/roman_khrystynych/FSCRH/
HTML:
<div id="container">
<div class="box">
<div class="button">Click</div>
</div>
</div>
jQuery:
$('#container').on("click", ".box", function(){
alert('box'); //only when anything in box except button
});
$('#container').on("click", ".button", function(){
alert('button'); //only when button clicked
});
Issue is that when clicking button the box element also activates its actions. Essentially I want it to be an exception that if I click on the button the regular box actions do no occur but instead the button actions occur. Any suggestions?
What you're talking about is event bubbling. When you click on a child element, it also triggers a click event on every single parent all the way up to the top of the DOM tree.
stopPropagation() will cancel bubbling up the dom tree
Try this:
$('#container').on("click", ".button", function(e){
e.stopPropagation()
alert('button'); //only when button clicked
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With