In the last video, a listener on the players list heard a click on every row, and event.target said where each click landed. You’ll need event.target once the list changes after the page loads. Tomás texted Priya this morning that he can come after all.
In this lesson, you’ll give Priya a way to add a late guest and check him in. Then you’ll replace the four Check in listeners with one on the list that handles every row, however late it arrived. Start with the field Priya needs to add him.
Add a Late Guest
Priya’s list is drawn once, at load, from the four guests in players, so a late guest needs another way onto the list. In scratch/index.html, add a labeled box and a button right after the arrival bar:
scratch/index.html
<label>
Late guest
<input id="late-guest">
</label>
<button id="add-guest">Add guest</button>
With the box inside its label, a screen reader announces “Late guest” for it, and clicking the words focuses the box.
Before you add code, tidy the end of main.js. Delete the last video’s two logging listeners, the list’s and the document’s. Section 1’s experiments still log six lines at each load, and the outputs below show only the lines clicks add.
The Add guest button’s listener builds a row the way drawPlayers() does, with a span for the name, then a Check in button carrying the guest’s ID and party size. Add it at the end of main.js:
scratch/main.js
const lateInput = document.querySelector("#late-guest");
const addButton = document.querySelector("#add-guest");
addButton.addEventListener("click", () => {
const name = lateInput.value;
const item = document.createElement("li");
const nameSpan = document.createElement("span");
nameSpan.textContent = name;
item.append(nameSpan);
const button = document.createElement("button");
button.textContent = "Check in " + name;
button.dataset.playerId = name.toLowerCase();
button.dataset.party = 1;
item.append(button);
playerList.append(item);
});
An input’s value holds the text currently in its box. The line reading it sits inside the listener, so it runs on each Add guest click. That’s all you need about reading a box for now. Forms come back later on.
Lowercasing the name gives Tomás the ID tomás, like wei and sam. He’s coming alone, so his party is 1.
Save and reload. Click Check in Wei first to see a working button. Then type Tomás in the box and click Add guest, and his row appears under Sam’s. Before you click Check in Tomás, predict what the Console will show, and then click. Here are the lines the two Check in clicks logged:
Checked in: wei
Arrived so far: 2