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...

user7685914
  • 83
  • 1
  • 9
  • 1
    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... – dandavis May 13 '17 at 12:40
  • Can you suggest a good source to learn about these on enough level please ? – user7685914 May 13 '17 at 12:44
  • 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. –  May 13 '17 at 12:44
  • 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 .. – user7685914 May 13 '17 at 12:49
  • 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 ``. That would mean you'd need to bind handlers not only to the `` but to all its `` children and all descendants of all `` 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. –  May 13 '17 at 12:53
  • 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 . But why it also walks up ? Am I missing something ? – user7685914 May 13 '17 at 13:00
  • 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? –  May 13 '17 at 13:18

0 Answers0