So far, we have been mostly using anonymous arrow functions as our event handlers, such as for button clicks. However, it's possible you might want to connect _multiple_ page elements to the same event handler, and in this case, you would use a named rather than an anonymous event handler function. A good example could be the "like" functionality, which could be linked to both a "Like" button and a "thumbs-up" image. You could link each to a named function, likeProduct():
document.getElementById('likeBtn').addEventListener("click", likeProduct);
document.getElementById('likeImg').addEventListener("click", likeProduct);
The question would then be: _how can the likeProduct() function retrieve the ID of that specific product?_ We could pass across the ID as a _data attribute_ to the button or image. A _data attribute_ is an HTML attribute which can be used to add aribtrary _data_ to an HTML tag. For example, here we are adding the data attribute data-id to both the button and the image, and setting it to the value 234:
<button id='likeBtn' data-id='234'>Like!</button>and:
<img id='likeImg' data-id='234' src='like.png'>Inside the
likeProduct() event handler we can then get hold of the data-id attribute of whichever element was clicked. To get hold of the element that was clicked, we can use the _event object_: an object which is passed into event handlers automatically as a parameter. The event object allows us to find out more about the event. Specifically here, we use its target property to find out the element that was clicked. Having done this, we then find the target's data-id attribute.
function likeProduct(e) {
const clickedElement = e.target;
const productId = clickedElement.getAttribute("data-id");
// now we have the product ID, continue...
}
setAttribute(). For example:
const likeBtn = document.createElement("button");
likeBtn.setAttribute("data-id", currentProduct.id);
likeBtn.addEventListener("click", likeProduct); // add the event listener, as before
// ... code continues ...