How to make a shopping cart in HTML,CSS & JavaScript?

How to make a shopping cart in HTML,CSS & JavaScript?

Shopping Cart is one of the basic JavaScript project a beginner should must build to brush up their JavaScript knowledge.

ยท

6 min read

Introduction

Shopping cart is one of the basic JavaScript projects a beginner front end developer must built in order to learn JavaScript and also to showcase their CSS skills.

A shopping cart involves JavaScript concepts like functions, loops, objects, arrays, array methods, it involves creation, deletion and updation in arrays and objects, so it can be a good addition to the resume of a beginner frontend developer.

What are we going to build?

We are building a shopping cart where we can add products, delete the products, increase and decrease the quantity of the products, and spontaneously calculate the total number of products in cart and total cart value.

We are focussing more on the Logical part rather than designing so I will be providing a link to the CSS file and just not wasting time in designing.

Let's get started.

Prerequisites

  • basic knowledge of HTML/CSS.
  • basic knowledge of JavaScript
  • a working computer
  • a text editor
  • a web browser

Initialization

  • Create a directory by the name of your choice.
  • Create a file named index.html in the directory we just created. Add the following HTML boilerplate code to it.
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Shopping Cart</title>
    <link rel="stylesheet" href="style.css" />
  </head>

  <body>
      <script src="app.js"></script>
  </body>
</html>
  • Create another file named app.js in the same directory.
  • At last create a file names style.css and paste the styles from the given GitHub repository.

Creating the HTML layout

Copy and Paste the following inside the body element.

<h1 class="">Shopping Cart</h1> 
    <div class="body">
      <div class="container">
        <h3 class="heading">Products</h3>
        <div class="result"></div>
      </div>
      <div class="cart">
        <div class="cart-header">
          <h3>CART</h3>
          <p class="noOfItems">0 items</p>
        </div>
        <hr noshade="true" size="1px" />
        <div class="cart-items"></div>
        <hr noshade="true" size="1px" />
        <div class="cart-footer cart-header">
          <h4>Total</h4>
          <p class="total">$0</p>
        </div>
        <button class="buy-btn">PROCEED TO BUY</button>
      </div>
    </div>

Layout Explanation

There is heading at the top. Then there is a div tag with class body which consists of two divs one containing the products and the other cart.

iMac - 1.png

Adding products array and mapping it

Copy and paste the following product array or you could make your own product array in the same format.

const products = [
  { name: "Adidas Shoes", price: 2500, id: 1, quantity: 1,},
  { name: "Sting Energy Drink", price: 120, id: 2, quantity: 1,},
  { name: "Umbrella", price: 500, id: 3, quantity: 1, },
  { name: "Cat Food", price: 900, id: 4, quantity: 1, },
  { name: "T Shirt", price: 300, id: 5, quantity: 1, },
  { name: "Book", price: 100, id: 6, quantity: 1,},
];

Now in app.js create a const named productsHTML and then map all the products in the products array and asssign it to productsHTML.

const productsHTML = products.map(
  (product) => `<div class="product-card">
        <h2 class="product-name">${product.name}</h2>
        <strong>$${product.price}</strong>
        <button class="product-btn" id=${product.id}>Add to Cart</button>
    </div>`
);

Now open index.html in your browser, It should look like this.

Screenshot (1297).png

Adding Products to Cart

Create an empty array cart , which we will be using to store cart items.

Rendering cart items

Now Create a function updateCart() to map and render cart items and call it to render the current items. Currently no change will be observed in web page since our cart is empty.

function updateCart() {
  const cartHTML = cart.map(
    (item) => `<div class="cart-item">
            <h3>${item.name}</h3>
            <div class="cart-detail"><div class="mid">
                <button onclick={decrItem(${item.id})}>-</button>
                <p>${item.quantity}</p>
                <button onclick={incrItem(${item.id})}>+</button>
            </div>
            <p>$${item.price}</p>
            <button onclick={deleteItem(${item.id})} class="cart-product" id=${item.id}>D</button></div>
           </div>`
  );

  const cartItems = document.querySelector(".cart-items");
  cartItems.innerHTML = cartHTML.join("");
}

updateCart();

Adding items to cart

Now we are going to create event listener which will be fired upon when we click add to cart button of a particular product.

We will also be getting the product id of the particular product which we wanna add to cart.

let num = document.querySelectorAll(".product-btn").length;
for (let i = 0; i < num; i++) {
  document
    .querySelectorAll(".product-btn")
  [i].addEventListener("click", function (e) {
    addToCart(products, parseInt(e.target.id));
  });
}

Now create a function named addToCart() to add items to cart on clicking the Add to cart button of a product with products and id as arguments.

function addToCart(products, id){
  const product = products.find((product) => product.id === id);
    cart.unshift(product);
    updateCart();
};

The function takes product and the particular product as argument which you want to add to cart.

We are using unshift() since we want to add newer items at the top. After adding new product to cart we are re-rendering the cart items to update the cart items on the webpage.

Calculating Total items and Total cart value

Now we will create a function named getTotal() to get total items and total cart value.

function getTotal(cart) {
  let { totalItem, cartTotal } = cart.reduce(
    (total, cartItem) => {
      total.cartTotal += cartItem.price * cartItem.quantity;
      total.totalItem += cartItem.quantity;
      return total;
    },
    { totalItem: 0, cartTotal: 0 }
  );
  const totalItemsHTML = document.querySelector(".noOfItems");
  totalItemsHTML.innerHTML = `${totalItem} items`;
  const totalAmountHTML = document.querySelector(".total");
  totalAmountHTML.innerHTML = `$${cartTotal}`;
}

Now update the addToCart() function by calling getTotal(cart); at the end of the function since we want to calculate and update total on adding each product.

We are calculating total items using reduce() method and then updating the data to the webpage.

Increasing and Decreasing quantity of cart items

Increasing quantity of items

Now we will create a function named incrItem() and pass id as parameter which we will be receiving when we click plus button of the particular cart product item.

function incrItem(id) {
  for (let i = 0; i < cart.length; i++) {
    if (cart[i] && cart[i].id == id) {
      cart[i].quantity += 1;
    }
  }
  updateCart();
  getTotal(cart);
}

!! Bug alert

As one can notice after clicking add to cart button of a particular button it should increase the no of product not add a new product in the cart.

Let's fix it by updating the function addToCart().

function addToCart(products, id){
  const product = products.find((product) => product.id === id);
  const cartProduct = cart.find((product) => product.id === id);
  if (cartProduct != undefined && product.id == cartProduct.id) {
    incrItem(id);
  } else {
    cart.unshift(product);
  }
  updateCart();
  getTotal(cart);
};

Decreasing quantity of items

Now we will create a function named decrItem() and pass id as parameter which we will be receiving when we click minus button of the particular cart product item.

function decrItem(id) {
  for (let i = 0; i < cart.length; i++) {
    if (cart[i].id == id && cart[i].quantity > 1) {
      cart[i].quantity -= 1;
    }
  }
  updateCart();
  getTotal(cart);
}

Notice quantity of a product cannot be less than one. So If we don't want to buy an item we can delete it instead making its quantity to zero.

Deleting Items from cart

Now we will create a function named deleteItem() and pass id as parameter which we will be receiving when we click delete button of the particular cart product item.

We are using splice() method to delete cart array item.

function deleteItem(id) {
  for (let i = 0; i < cart.length; i++) {
    if (cart[i].id === id) {
      cart[i].quantity = 1;
      cart.splice(i, 1);
    }
  }
  updateCart();
  getTotal(cart);
}

Finishing it!

The finished project should look like this:

If you ran into a problem or got bugs in your project, you can check out the finished project here.

Check out the finished project here

Thank you for reading this article ๐Ÿ˜Š.

Please feel free to ask questions in the comments below.

ย