In this example, the element with the id of “mySelector” is clicked on and that click event triggers the console.log function to print out the message. This is simple. The html code for this element is this.
Here’s where the problems start arising. What if you had a list of elements in your document and you wanted your function to fire whenever any of those elements was clicked?
Simple, you might think, let’s just add a class to each <li> element and fire off the code whenever the click event occurs on that element. Let’s see how this would look.
Now, the html:
So, now when any one of those elements is clicked, the function will fire. Great! It works. But here’s the catch - what if this list was actually a todo list, and each element in the list was either added or removed dynamically? Let’s look at the code for this.
This function is nothing special, it merely appends a new item to the todo list. For the sake of this example, let’s just say we only call it once and only add one item to our 3 item list.
Resulting html code after the addItem function is fired:
You might be thinking to yourself, “great, we have a working todo list now!” Not so fast. If you click on items 1 through 3 in your list, you’ll still fire the click event logging “You clicked an item” to the console. But, here’s the twist. If you click item 4, nothing happens. Uhhhhh…what? Let’s take a closer look at what’s going on here.
Your initial html code was this:
With that being said, when we ran our addItem function, the resulting code on the page was
But, the code in the DOM was
So, lets change up our original event listener to start listening for click. This time, we’re going to pass in a couple different selectors to make things a bit easier.
Now, we have a working app. What the code above does is listen for clicks on the parent element of the list you want to add to. Since that element will always be in the DOM, you will always hear when the clicks happen. Once it hears a click, it moves down to see if what you clicked on has a class of “mySelector,” if it does, your function runs. If it doesn’t, nothing happens.