Crossing Off Items

In the shop, it's handy to cross off what's already in your cart. In this exercise, clicking an item marks it as bought, and the page shows it crossed out. Clicking it again unmarks it.

Whether an item is bought is information about the item, so it belongs in its object, as a new property bought with the value true or false: { name: "Milk", price: 2, bought: false }. showItems() then gives the li of every bought item the class bought from the page's style, which crosses it out. Since item.bought is already true or false, it can be the condition by itself: if (item.bought) means the same as if (item.bought === true).

Why not simply add the class when the item is clicked? Because showItems() creates all the li elements anew whenever the list changes. The class would disappear with the old li as soon as you added another item. The objects in the array stay, so the information must be stored there. The rule from the beginning of the project still holds: change the data, then show the page again.

Now the clicking. Inside the loop in showItems(), give each li its own click handler. The function is created inside the loop, so it remembers the item from that iteration of the loop: clicking the milk changes the milk. The ! operator turns true into false and back:

li.addEventListener("click", () => {
    item.bought = !item.bought;
    showItems();
});

The handler calls showItems() so that the page shows the change. Calling showItems() from inside showItems() is fine here: the handler doesn't run while the list is being shown, only later, when you click the item.

Instructions

Add the property bought to every object in items: true for the bread (say it's already in your cart) and false for the others. Add bought: false to the new object in the click handler of the Add button, too. Then, in showItems(), give the li the class bought (li.classList.add("bought")) if the item is bought. The bread appears crossed out.

In showItems(), add a click handler to each li that switches item.bought to the opposite value and calls showItems(). Click the items to try it.

Start programming for free

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

Or sign up with:

5/6