JavaScript — Event Bubbling and Delegation
This article is one the more important ones. This is something that you could easily turn a blind eye to when learning JavaScript, but it WILL come back to bite you later. So lets get it learned!
When an event occurs… that element becomes the event target. When that happens, JavaScript will basically check to see if there are any event listeners attached to that element.. if there are, the callback function gets fired off.
In this example, each li
element gets an event listener added that is looking for click events when the page loads. This isnt the end of the stroy though..
After the callback function fires off, the event “bubbles up” to the parent element. In this case, the ul
. If the ul
has an event listener added, this event will be fired off too.. This isn’t what you always want. So to see this in action..
Here I have added an event listener to each of the li tags and an event listener to the ul. When I run this and click one of the li elements, the ul log will print out as well.
So if we don’t want this to happen we can stop it from happening using the stopPropogation()
. Like this:
Now the ul
's event wont fire off.
So this is event bubbling. Its something to be aware of when you sdtart getting trigger happy with your event listeners. Another thing pretty closely related to event bubbling is event delegation:
If there were multiple lis I wanted to be able to click, it would get pretty cumbersome to assign event listeners to each set of them. Its not great practice and it could effect the performance of our program, SO
I’ve removed the event listeners from the li tags. I’ve only got a single event listener on the ul.
When I click a li, the e.target should print out which one I clicked.
In the last article I mentioned that we needed to figure out a way to add event listners to each of the NEW li tags that appear when we click the button:
Code in case you don’t have it:
The problem we faced before was that each element with an li tag was assigned an event listener when the page loads. The new ones wouldn’t get event listeners though. Adding the event listener to the ul
solves this because the eventListener isn’t actually ON the li
element. So the e.target
is printed regardless.
So if I want to remove the li tag I just clicked I can use the e.target.tagName property.
Now, if I click a li
element it will be removed. When I click the button a new one is added to the list. This newly added li
is also clickable and will be removed.