Late guests’ rows join the list after drawPlayers() has run its loop, so their buttons would get no listener. In this video, you gave a listener its event parameter and followed a click on Wei’s Check in button up through the page, to see whether one listener higher up could hear every row. Here are the key points:
- The browser calls every listener with one argument, an event object, which describes what happened. Give the arrow a parameter, named
eventby most code, to use it. The object holds more than the properties below, but they’re all you need for now. Once you delete the log lines, you can leave the parameter in place. Unused, it does no harm. event.typeis the kind of event,clickhere.event.targetis the element the click landed on. In the Check in button’s own listener, that’s Wei’s button.- A click travels up the page’s tree. It starts at the element it lands on, then moves through every element that element sits inside: Wei’s list item, the players list,
main,body,htmland the document. This trip is called bubbling. - Every click listener on the way runs, from the button outward. A click on Wei’s Check in button logs the button’s own two lines, then the list’s line, then the document’s.
event.currentTargetis the element whose listener is running. The target stays the same all the way up, and the current target changes at each listener on the way. In the list’s listener, the target is still Wei’s button, and the current target is the list, whose id isplayers. The code logs the list’s id because its text would be every row at once.- With a mouse, the target is the innermost element under the pointer, which isn’t always a button. A click on Sam’s name makes the
spanthat holds it the target. Sam’s Check in listener doesn’t run, because the button isn’t above thespanin the tree. Press Enter or Space on a focused button, and the target is the button. - Browsers also make an earlier pass down the tree, called capture. Listeners run on it only if you opt in. That’s all you need about capture for now.
At the end of main.js, below everything else, add the two listeners. playerList is already declared near the top of the file:
playerList.addEventListener("click", (event) => {
console.log("Target:", event.target.textContent);
console.log("Current target:", event.currentTarget.id);
});
document.addEventListener("click", () => {
console.log("Document heard a click");
});
Save, reload, and click Wei’s Check in button. Below the lines that section 1’s experiments log as the page loads, the Console shows the button’s own two lines, then the list’s two lines, then the document’s line: