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", function () {
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
- 1
Add the property
boughtto every object initems:truefor the bread (say it's already in your cart) andfalsefor the others. Addbought: falseto the new object in the click handler of the Add button, too. Then, inshowItems(), give thelithe classbought(li.classList.add("bought")) if the item is bought. The bread appears crossed out. - 2
In
showItems(), add a click handler to eachlithat switchesitem.boughtto the opposite value and callsshowItems(). Click the items to try it.