Week 5 Cheatsheet: Add to Cart with JavaScript
What You’re Building
A working Add to Cart button. Clicking it adds a product to your cart.
JavaScript Concepts
addEventListenerdataset.idto get product ID.find()to look up a product.push()to add to an array
Example Code
const cart = [];
function addToCart(productId) {
const product = products.find((p) => p.id === productId);
const existingItem = cart.find((item) => item.id === productId);
if (existingItem) {
existingItem.quantity++;
} else {
cart.push({ ...product, quantity: 1 });
}
updateCart();
}
document.querySelectorAll(".add-to-cart-button").forEach((button) => {
button.addEventListener("click", () => {
addToCart(button.dataset.id);
});
});Tips to Remember
- Use
data-idin your HTML to track each product - Always call
updateCart()after changing the cart - Each product in
cartshould include aquantityproperty
Last updated on