Start learning free

LESSON 35 OF 161 · FRONTEND: JAVASCRIPT IN THE BROWSER

Which Button Was It? in JavaScript

Practice

The product list has eight Add to cart buttons. Instead of eight listeners, put one listener on the list. A click bubbles: it starts at the button, then reaches the li around it and the ul around that, so the list hears every click inside it.

In the listener, event.target is the element the visitor really clicked. Here is a listener on another element, the footer:

const footer = document.querySelector("footer");
footer.addEventListener("click", (event) => {
  console.log("clicked: " + event.target.textContent);
});

event.target.closest("li") walks up from the clicked element to its card. The card's data-id, read with dataset.id, says which product it is; it is always a string, so turn it into a number with Number before comparing. event.target.matches("button") tells you whether the click was on a button.

The check clicks two buttons, then a product's name, and must print:

> click "Add to cart" in "Mug"
    +   text: Mug added
> click "Add to cart" in "Lamp"
    -   text: Mug added
    +   text: Lamp added
> click "Teapot"
  screen: no change

Your task: in productCard, give each card a data-id with its product's id. Add one click listener to the list: when a button is clicked, find its card, then the product with that id in PRODUCTS, and write the product's name followed by " added" into p#message. A click anywhere else in the list does nothing.


Assignment
Follow the Coding Tutorial to put the id on each card, add the list's click listener, and show which product was added.


Hint
"3" === 3 is false: read the id with Number(card.dataset.id). The guard that skips clicks on names and prices goes at the very top of the listener.


STEP 1 OF 8
    Ctrl + Enter to check

    Dom Event Target in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free