Build a Shopping Cart with JavaScript – Project Tutorial
Table of Contents
Introduction
In this tutorial, you will learn how to build a fully functional shopping cart using vanilla JavaScript. This project covers various essential aspects of web development, including handling user interactions, managing data with local storage, and dynamically updating the DOM. By the end of this tutorial, you'll have a clear understanding of how to create a shopping cart application from scratch.
Chapter 1: Setting Up Your Environment
-
Create a New Project Folder
- Right-click on your desktop or desired location.
- Create a new folder and name it
shopping-cart
.
-
Open the Project in Visual Studio Code
- Right-click the folder and select "Open with VS Code".
- If the option is not available, open VS Code and manually select the folder.
-
Download Starter Files from GitHub
- Access the provided GitHub repository link.
- Download the starter files as a ZIP and extract them.
- Move the
images
folder anddata.js
file into your project folder.
-
Create Necessary Files
- Create three files:
index.html
,style.css
, andmain.js
.
- Create three files:
-
Set Up Basic HTML Structure
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <title>Clothing Store</title> </head> <body> <h1>Hello World</h1> <script src="main.js"></script> </body> </html>
Chapter 2: Creating the Navbar
-
Create the Navbar Structure
- Inside
index.html
, replace the<h1>Hello World</h1>
with the navbar HTML using Emmet:
<div class="navbar"> <h2>Clothing Store</h2> <div class="cart-icon"> <i class="bi bi-cart"></i> <span class="cart-amount">0</span> </div> </div>
- Inside
-
Style the Navbar
- Add the following CSS in
style.css
to style the navbar:
.navbar { display: flex; justify-content: space-between; background-color: #212529; padding: 25px 60px; color: white; }
- Add the following CSS in
Chapter 3: Product Cards
-
Add Product Cards Structure
- Below the navbar in
index.html
, create a container for product cards:
<div id="shop" class="shop"> <!-- Product cards will be generated here --> </div>
- Below the navbar in
-
Define Product Data in
data.js
- Store your product data in
data.js
:
const shopItemsData = [ { id: "item1", name: "Casual Shirt", price: 45, img: "images/casual-shirt.jpg" }, { id: "item2", name: "Formal Shirt", price: 100, img: "images/formal-shirt.jpg" }, // Add more items as needed ];
- Store your product data in
-
Generate Product Cards Using JavaScript
- In
main.js
, create a function to generate product cards:
function generateShopItems() { const shop = document.getElementById("shop"); shop.innerHTML = shopItemsData.map(item => ` <div class="item"> <img src="${item.img}" alt="${item.name}" width="200"> <h3>${item.name}</h3> <p>$${item.price}</p> <button onclick="addToCart('${item.id}')">Add to Cart</button> </div> `).join(''); } generateShopItems();
- In
-
Style Product Cards
- Add CSS for the item class in
style.css
:
.shop { display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; } .item { border: 2px solid #212529; border-radius: 4px; padding: 10px; text-align: center; }
- Add CSS for the item class in
Chapter 4: Shopping Cart Functionality
-
Implement Add to Cart Function
- Create a function in
main.js
to add items to the cart:
let cart = []; function addToCart(id) { const item = shopItemsData.find(item => item.id === id); const existingItem = cart.find(cartItem => cartItem.id === id); if (existingItem) { existingItem.amount++; } else { cart.push({ ...item, amount: 1 }); } updateCart(); }
- Create a function in
-
Update Cart Display
- Create an update function to update the cart view:
function updateCart() { const cartIcon = document.querySelector('.cart-amount'); cartIcon.innerText = cart.reduce((total, item) => total + item.amount, 0); }
-
Implement Local Storage
- Use local storage to save cart data:
function saveToLocalStorage() { localStorage.setItem("cart", JSON.stringify(cart)); } function loadFromLocalStorage() { const storedCart = JSON.parse(localStorage.getItem("cart")); if (storedCart) { cart = storedCart; updateCart(); } } loadFromLocalStorage();
Chapter 5: Cart Page
-
Create Cart Page Structure
- In
cart.html
, create the structure for displaying cart items:
<div id="cart" class="cart"> <h2>Your Cart</h2> <div id="cart-items"></div> <h3>Total: <span id="total-amount">$0</span></h3> <button onclick="clearCart()">Clear Cart</button> </div>
- In
-
Generate Cart Items
- In
main.js
, create a function to display cart items:
function generateCartItems() { const cartItemsContainer = document.getElementById("cart-items"); if (cart.length === 0) { cartItemsContainer.innerHTML = "<p>Your cart is empty.</p>"; return; } cartItemsContainer.innerHTML = cart.map(item => ` <div class="cart-item"> <h3>${item.name}</h3> <p>Price: $${item.price}</p> <p>Quantity: ${item.amount}</p> <button onclick="removeFromCart('${item.id}')">Remove</button> </div> `).join(''); }
- In
-
Implement Remove from Cart Function
- Add functionality to remove items from the cart:
function removeFromCart(id) { cart = cart.filter(item => item.id !== id); updateCart(); generateCartItems(); }
-
Implement Clear Cart Function
- Create a function to clear the cart:
function clearCart() { cart = []; updateCart(); generateCartItems(); }
Conclusion
You have successfully built a shopping cart application using vanilla JavaScript. The application allows users to add products to their cart, view the cart, and manage the items within it. Additionally, local storage is utilized to persist cart data across page refreshes. As a next step, consider enhancing the UI further or adding more features like user authentication or payment processing. Happy coding!