JQuery parent and child divs that trigger different actions

I have an element that contains many components inside it. Lets you call this item. Now inside the box I have many different elements, images, 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 }); 

The problem is that when a button is clicked, the window element also activates its actions. Essentially, I want this to be an exception, if I click on a button, normal mailbox actions do not occur, but button actions act instead. Any suggestions?

+4
source share
2 answers

What you are talking about is an event bubble. When you click on a child, it also fires a click event for each individual parent right up to the top of the DOM tree.

stopPropagation () will cancel the dom tree skidding

Try the following:

  $('#container').on("click", ".button", function(e){ e.stopPropagation() alert('button'); //only when button clicked }); 
+6
source

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

stopPropagation();

it stops the click event from bubbles.

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

+2
source

Source: https://habr.com/ru/post/1468784/


All Articles