How to prevent damage to the child from the parent

How to prevent the influence of the CHILD element on the PARENT element?

JQuery

$("#parent").click(function() { alert('parent clicked'); }); $("#child").click(function() { alert('child clicked'); }); 

HTML:

 <div id="parent"> click me - parent <div id="child">click me - child</div> </div> 

If you click on a child, the parent is also activated, and we have 2 warnings.

So, how can I prevent a child from influencing a parent?

+6
source share
2 answers

event.stopPropagation ()

 $("#child").click(function(event) { event.stopPropagation(); alert('child clicked'); }); 

Calling event.stopPropagation() will stop the event from the bubbles of the DOM tree.

+10
source

This is called event bubbling or event propagation . This can be prevented by adding e.stopPropagation() to your code. If you also want to stop the default behavior, you can simply do: return false; .

return false; basically does both: e.stopPropagation() and e.preventDefault() . Which may be useful if you use <a> tags, for example, and want the page to not move after clicking.

+3
source

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


All Articles