The Event Object

When the browser runs a handler, it gives the function an argument: an object that describes what has just happened. It's called the event object. To use it, give the handler a parameter. You can call it whatever you like, but it's usually called event:

const helloButton = document.querySelector("#hello");

helloButton.addEventListener("click", function (event) {
    console.log(event.type);
    console.log(event.target);
});

With the button <button id="hello">Say hello</button>, a click prints:

click
<button id="hello">Say hello</button>

event.type is the name of the event, and event.target is the element where it happened, here the button that was clicked. The handlers you wrote in the previous lesson had no parameter. The browser gave them the event object too; they just didn't use it.

Why do you need event.target when the button is already in a variable? Because one function can handle several elements, and event.target tells it which one it's handling right now. Here's a poll with two buttons and one handler:

const answer = document.querySelector("#answer");
const yesButton = document.querySelector("#yes");
const noButton = document.querySelector("#no");

function vote(event) {
    answer.textContent = `You voted: ${event.target.textContent}`;
}

yesButton.addEventListener("click", vote);
noButton.addEventListener("click", vote);

A click on Yes shows You voted: Yes, and a click on No shows You voted: No. The function is the same, but each time, event.target is the button that was clicked. As you know, you pass the function by its name, without parentheses: the browser calls it and gives it the event object.

event.target is an element like any other, so it has textContent, classList, style and everything else you know from the previous lesson.

Instructions

Write a function pickFlavor(event) that shows Your ice cream: Chocolate in choice, but with the text of the clicked button instead of Chocolate. Make it the click handler of all three buttons, and try them.

Mark the flavor you picked. In pickFlavor(), remove the class chosen from all three buttons, and then add it to event.target. The page's style makes the chosen button gold, and only one of them is gold at a time.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

1/10

Next