Understanding how event delegation/propagation works in JS
The confusion is our parent container is registered as an event listener but when we click on one of its child element, the target recognise the element as if it was also registered; can someone explain why is it so please.
10 Replies
I'd explain it, but MDN does a much better job: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Event_bubbling
MDN Web Docs
Event bubbling - Learn web development | MDN
We've seen that a web page is composed of elements — headings, paragraphs of text, images, buttons, and so on — and that you can listen for events that happen to these elements. For example, you could add a listener to a button, and it will run when the user clicks the button.
Yep I had a look at that, the only thing that I didn't understand is that normally, when we assign an event listener to a parent element, when we say click on one of its child element, the event bubbles up until the parent; this is what is known as event bubbling. The thing is when we use
event delegation
, the reverse seems to happen. That is, from the parent, we move downwards until a target element and without using the keyword capture; I'm a bit confuse about thatthe event fires on the child then bubbles up to the parent, where it triggers an event handler
the bubbling happens regardless of whether an event handler is assigned or not
Ah I see, the event handler is just to take some actions ?
hmm when you say the event fires on the child, the thing is we don't have any event registered on that particular element, how does the javascript engine knows that we click on that element
the event firing has nothing to do with us registering handlers for it, it happens all the time for every event that could possibly happen. When you click anything, for example, the javascript engine goes through the element and all its parents to check if there's a handler for that element, and if there is, it runs it
Ah I see, so each time we click on something for e.g, an event is fired irrespective if we have an event handler or not ?
yes
by registering a handler, we're just hooking into the existing event system and letting JS know we want to run some code when that event happens
Yep I see, the missconception was that I thought an event is fired only for registered events (that is on element on which we use addEventListener) but this isn't the case....I also understood how the event delegation works thanks to that... so we can click on a child element, then this event is bubbled up to the parent element (I always thought that the starting point was always the parent element then going down)
yup, that's correct!
Thanks, my doubts have been cleared, really appreciate ! 💯