JavaScript Event Delegation

The Art of JavaScript Event Delegation 

Taking the same example as before, let’s try out an approach called event delegation. Instead of creating individual event handlers for each element we want to target, we will be assigning one event handler to a parent element and specifying conditions for which elements will be impacted by that event.

Our createColorfulButtons(), HTML, and CSS are exactly the same, but this time let’s add an event listener outside the scope of our forEach and directly to our buttonContainer.

buttonContainer.addEventListener("click", function(e){
console.log(e.target)
})

If you try clicking on the different buttons, you’ll see that e.target refers to the element being clicked on, and that our console.log will print that specific element.

For example, if we click directly on the button that says “pink”, it will print <button> pink </button> . If we click on the area outside the button, on on of our li elements, the following will be printed into the console: <li><button> pink </button></li> .

buttonContainer.addEventListener("click", function(e){  if(e.target.tagName === "BUTTON") {
console.log(e.target)
}
})
Now when you try clicking on anything besides a button, nothing gets printed to the console. We’ve isolated our buttons! You might be wondering about where the .tagName is coming from. .tagName is one of many properties that can be used on an element (and therefore on e.target).
buttonContainer.addEventListener("click", function(e){

if(e.target.tagName === "BUTTON") {
let buttonText = e.target.innerText;
e.target.classList.toggle(buttonText)
}

})

Comments