Objectives

At the end of this module, you should be able to:

Starter Code

Solution Code

Todo list event bubbling and delegation example

https://codepen.io/cgorton/pen/aeEyVe

Instructor Notes

Step 1:

Review different events

const catImage = document.querySelector(".card-img-top");
console.log(catImage);
// mouse events
catImage.addEventListener("mouseenter", () => {
 catImage.style.transform = "scale(1.2)";
 catImage.style.transition = "all 0.3s";
})
catImage.addEventListener("mouseleave", () => {
 catImage.style.transform = "scale(1)";
})
// click event on multiple elements
document.querySelectorAll(".card-title").forEach(el => {
  el.addEventListener("click", () => {
        el.style.transition = "color 0.5s";
        el.style.color = "#e62739";
    })
    });
// single click event
const changeImg = document.querySelector(".logo");
changeImg.addEventListener("click", () => {
 changeImg.src="<https://s3-us-west-2.amazonaws.com/s.cdpn.io/780593/cat-lambda.png>";
})
console.log(changeImg)

Step 2:

Showcase event propagation and the event object

We will set up a way to show event propagation and then how to prevent it. First we need to add click events to several elements that are nested. The body, the card-group, and the card.

const body = document.querySelector("body");

body.addEventListener('click', () => {
  body.style.backgroundColor="papayawhip";
  console.log("end")
});
const cardGroup = document.querySelector(".card-group");

cardGroup.addEventListener('click', () => {
  cardGroup.style.backgroundColor="rebeccapurple";
  console.log("middle")
});
const card = document.querySelector(".card");

card.addEventListener('click', (event) => {
  card.style.backgroundColor="hotpink";
  console.log("start")
  event.stopPropagation() // if removed the events will fire 
                          // on all of the proceeding elements too
});

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/4effa7a1-03c8-4da1-94d1-e329d7b3c59b/event_bubbling.png