Does the child fire a click event with the parent in jquery?

if I have a field with a floating message and I wonder if clicking a paragraph text in this field will also register a click on its parent element in jQuery or if I have to add clicks for child elements.

update: here is the main layout:

<div id='msgbox'> <p>This is the <span>message</span></p> </div> 

Now, if I press the text in <p> or in <span> , will it still start by pressing the $('#msgbox') button?

update 2: Can I stop this behavior?

update 3: here is the fiddle I went with: http://jsfiddle.net/MZtbY/ - is there now a way to stop the spread after it reaches a certain level? so clicking <p> would be ok, but pressing <span> do nothing? - sort of like $('#msgbox :nth-child').click(function(e) {e.stopPropagation();});

+6
source share
3 answers

Here is an example in jsFiddle

 $('#msgbox').click(function(evt){ alert("click on msgbox: "+evt.target); }); // stop bubbling for the span only. $('#msgbox span').click(function(evt) { evt.stopPropagation(); }); 

Note that pressing the #msgbox <div> button (red box in jsFiddle) or in the first section of the paragraph text will call the event handler on #msgbox; but clicking on the text inside the <span> will not. This is because we applied the handler directly to the span and called stopPropagation() in this case to prevent the normal action of the bubbles.


Update : here is an update to your violin that shows the same thing.

+5
source

The default event is "bubble" in JavaScript. They fire at the level that you run, and then one at a time through the parent elements.

More on event bubbles: http://www.quirksmode.org/js/events_order.html

To Stop It: Preventing "Bubbling"?

+2
source

If you want to stop it when using bbbling, use

 e.stopPropagation(); 
+2
source

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


All Articles