4

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?

BBagi
  • 2,035
  • 1
  • 19
  • 23

2 Answers2

6

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
    });
BBagi
  • 2,035
  • 1
  • 19
  • 23
2

jquery has a function for it. http://api.jquery.com/event.stopPropagation/

stopPropagation();

it stops the click event from bubbling.

http://jsfiddle.net/honk1/FSCRH/1/

honk31
  • 3,895
  • 3
  • 31
  • 30