Why we need to use stopPropagation in javascript events?
Asked Answered
F

0

0

There are ways of registering Events to objects in an HTML file. So this way an object is set to detect events.

In case we think 2 div elements one inside other; If i attach an onClick event to inner div; this means outer div was not attached one. So it should NOT detect the click event. Why still we need to use stopPropagation () ? since we did not attach any other event detection...

Fractionize answered 13/5, 2017 at 12:35 Comment(7)
you don't need to use stopPropagation() very often, and if you find yourself needing to, you're doing your events wrong and need to brush up on delegation and the bubbling models. look up the third "optional" argument to addEventListener, and give it an hour to sink in...Yvette
Can you suggest a good source to learn about these on enough level please ?Fractionize
If you click the inner one, you're also clicking the outer one. Why do you think it "should NOT" detect the click? Are you saying the event system should be designed so that you must explicitly bind a handler to every single descendant of the element you want clicked? That would be terrible.Margitmargo
Squint...If i want to detect the click on outer one; I would attach the event to outer one.. I don't understand why it keeps waving through the elements. In this case using event handlers comes out irrelevant. So why we need them ? I am trying to understand if there is a logical answer to this ..Fractionize
Because with your way, when you do want to handle all clicks inside an element, you'd need to bind to every descendant. Imagine you want to handle all clicks on a table's <tr>. That would mean you'd need to bind handlers not only to the <tr> but to all its <td> children and all descendants of all <td> elements. That would be obnoxious, especially when it is more natural to say when you click a child, you're also clicking its ancestors, which is true.Margitmargo
But the case is different here. I add even listener to child and it bubbles up. So in case of your example. I attach a event to a td and it is triggering the event on its table..I can understand the case if i attach a click to table and it walks down to <td> . But why it also walks up ? Am I missing something ?Fractionize
How could it tell the difference? How would it know what you're thinking? Clearly they needed to decide one way or the other. Imagine if you have an event handler on the outer div, but then some other code puts a handler on something else inside that div, why should it prevent your handler from working when clicking that inner element? What if you nested handlers intentionally and want both to be invoked? Then what would you do?Margitmargo

© 2022 - 2024 — McMap. All rights reserved.