Skip to Content
🤝 Want to bring tech2elevate to your company or school? Partner with us
CurriculumWeek 5Cheat Sheet

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

  • addEventListener
  • dataset.id to 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-id in your HTML to track each product
  • Always call updateCart() after changing the cart
  • Each product in cart should include a quantity property
Last updated on