How to Add to Cart in JavaScript (Step-by-Step)

How to Add to Cart in JavaScript

Ever browsed an online store, clicked “Add to Cart,” and wondered “How does that even work?”
Well, today you’re going to learn how to build that feature yourself using plain JavaScript.

I still remember the first time I built a shopping cart—my code was messy, but it worked! 😅 Let me save you the pain and walk you through it in a way that’s clear, fun, and practical.

What You’ll Learn

  • Creating a basic product layout
  • Adding items to a cart using JavaScript
  • Storing the cart in the browser
  • Updating cart totals
  • Best practices

Tools You’ll Use

  • HTML5 & CSS3 for structure and styling
  • Vanilla JavaScript to manage the cart logic
  • Optionally, browser’s LocalStorage to save the cart

🔰 New to web dev? Start with my HTML5, CSS3 & JavaScript Course
It’s beginner-friendly and packed with practical exercises!

Basic Layout (HTML + CSS)

Here’s the structure for your products:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Simple Cart</title>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet">
  <style>
    body {
      font-family: 'Inter', sans-serif;
      padding: 30px;
      background: #f9f9f9;
    }

    .product {
      display: flex;
      align-items: center;
      gap: 15px;
      background: #fff;
      padding: 20px;
      margin-bottom: 15px;
      border-radius: 10px;
      box-shadow: 0 0 10px rgba(0,0,0,0.05);
    }

    .product img {
      width: 100px;
      height: auto;
      border-radius: 6px;
    }

    button {
      padding: 10px 20px;
      background: #0070f3;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
    }

    #cart {
      margin-top: 30px;
      padding: 20px;
      background: #fff;
      border-radius: 10px;
    }
  </style>
</head>
<body>

  <div class="product">
    <img src="https://picsum.photos/100" alt="Product">
    <div>
      <h3>Product 1</h3>
      <p>₹500</p>
      <button onclick="addToCart('Product 1', 500)">Add to Cart</button>
    </div>
  </div>

  <div id="cart">
    <h2>Your Cart</h2>
    <ul id="cart-items"></ul>
    <strong>Total: ₹<span id="cart-total">0</span></strong>
  </div>

  <script>
    let cart = [];

    function addToCart(name, price) {
      cart.push({ name, price });
      renderCart();
    }

    function renderCart() {
      const cartItems = document.getElementById('cart-items');
      const cartTotal = document.getElementById('cart-total');
      cartItems.innerHTML = '';
      let total = 0;

      cart.forEach((item) => {
        const li = document.createElement('li');
        li.textContent = `${item.name} - ₹${item.price}`;
        cartItems.appendChild(li);
        total += item.price;
      });

      cartTotal.textContent = total;
    }
  </script>

</body>
</html>
Code language: HTML, XML (xml)

How It Works

  • When you click “Add to Cart”, the product is added to an array called cart.
  • The function renderCart() updates the cart display and total amount.
  • This example keeps it simple—ideal for understanding the core concept.

Make It Persistent with LocalStorage

Want your cart to stay even after page reload? Use this:

function addToCart(name, price) {
  cart.push({ name, price });
  localStorage.setItem('cart', JSON.stringify(cart));
  renderCart();
}

window.onload = () => {
  const storedCart = localStorage.getItem('cart');
  if (storedCart) {
    cart = JSON.parse(storedCart);
    renderCart();
  }
};
Code language: JavaScript (javascript)

💡 Want to dive deeper into local storage and client-side storage?
My JavaScript Mastery Course and Modern JavaScript Course cover everything in depth.

Add More Features

Here are ideas to make it production-ready:

  • Quantity updates
  • Remove item from cart
  • Show product images and icons (use https://iconoir.com/)
  • Checkout functionality

🛍 Planning to build an online store?
Check out my WooCommerce Course or WordPress WooCommerce Course.

Recommended Learning Path

Depending on your current level, here’s how to grow your skills:

Beginners:

Intermediate:

Projects & E-commerce:

Recap

You now know how to:

  • Create a cart in JavaScript
  • Add and render items dynamically
  • Use LocalStorage to persist data
  • Style your layout cleanly and responsively

🎓 Ready to turn this into a real-world project?
Enroll in the Web Design Development Course to build more interactive UI components!

Next Steps

This is just the beginning. Try expanding this mini-project into a full e-commerce prototype with:

  • Multiple products
  • Quantity management
  • Cart badge in the navbar

Trust me, once you nail this, JavaScript becomes way more fun. And if you ever get stuck, revisit this guide or join my JavaScript Mastery Course for deeper insights and more mini-projects!


Discover more from Prime Inspire

Subscribe to get the latest posts sent to your email.

We’d love to hear your thoughts! Share your ideas below 💡

Scroll to Top

Discover more from Prime Inspire

Subscribe now to keep reading and get access to the full archive.

Continue reading