Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery parent and child divs activating different actions

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?

like image 332
Roman Khrystynych Avatar asked Feb 18 '23 05:02

Roman Khrystynych


1 Answers

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
    });
like image 200
BBagi Avatar answered Mar 24 '23 04:03

BBagi