Loading.......
Loading...

How to make a Shopping Cart in HTML, CSS & JavaScript

Posted on 22nd October, 2025
CART SHOPPING CART HTML SHOPPING CART CSS SHOPPING CART JAVASCRIPT SHOPPING CART ONLINE SHOPPING CART

Introduction

This tutorlal focuses on how to build a shopping cart using HTML, CSS and JavaScript with the help of localStorage in JavaScript to temporarily hold or store the products or items in the shopping cart until they are finally saved in a permanent database at the server side.

Definition and Functionality

The shopping cart is a virtual basket where customers can add products they want to buy while browsing an ecommerce site. It typically displays the selected items, quantities, prices, and an option to proceed to checkout. The shopping cart is a crucial step in the online purchasing process.

Importance in User Experience

A well-designed shopping cart enhances the user experience by making it easy for customers to review their selections, make changes, and proceed to checkout. Features like saving items for later, displaying total costs (including taxes and shipping), and providing quick access to checkout can reduce cart abandonment and improve conversion rates.

Optimizing Shopping Cart Functionality

To optimize the shopping cart, businesses should ensure it is easy to use, accessible from any page, and provides clear, transparent pricing. Offering features like guest checkout, real-time inventory updates, and personalized recommendations within the cart can also improve the shopping experience and increase sales.

Building the Shopping Cart

We are going to build a shopping cart where users can do the following:
  • Add products to cart
  • View the products already added in the cart
  • Update products in the cart by increasing or decreasing the quantity of the products
  • Remove a desired product from the cart if need be
  • Calculate the total number of products in the cart
  • Calculate the total price of the products in the cart

Requirements

  • Basic knowledge of HTML & CSS.
  • Basic knowledge of JavaScript
  • A working computer
  • A text editor
  • A web browser

Let's get started.

We created a directory and named it cart
We created a file and named it index.php in the directory we just created.
We added the needed HTML codes, below is an example with a link in the head section of the HTML file pointing to our CSS file and also a link just before the body section of our HTML file pointing to our JavaScript file

DISPLAYING PRODUCTS IN OUR SHOP

<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>Easy Shopping Cart using HTML,CSS & JavaScript</title>
    
    <!-- This is a link to our CSS file -->
    <link rel="stylesheet" href="css/style.css" />
  </head>

  <body>
  
  <!-- First Product in the shop -->
  <div class="col-lg-3 col-md-6">
          <div class="featured-item">
             <div class="featured-item-img">
                <a href="#">
                   <img src="img/women-1.jpg" alt="Images">
                </a>
             </div>
             <div class="content">
                <h3><a href="#">Tunic </a></h3>
                <hr>
                <div class="content-in">
                   <h4>$ 459 </h4>
                   <span>(4.4)<i class='fa fa-star' style='color:green'></i></span>
                </div>
                <hr>
                <div class="featured-content-list">
                   <button type="button" data-name="Tunic" data-price="459" class="default-btn border-radius-5">Add to cart</button>
                </div>
             </div>
          </div>
       </div>
       
       <!-- Second Product in the shop -->
       <div class="col-lg-3 col-md-6">
          <div class="featured-item">
             <div class="featured-item-img">
                <a href="#">
                   <img src="img/watch-1.jpg" alt="Images">
                </a>
             </div>
             <div class="content">
                <h3><a href="#">Huawei Watch Buds	</a></h3>
                <hr>
                <div class="content-in">
                   <h4>$ 4059 </h4>
                   <span>(4.4)<i class='fa fa-star' style='color:green'></i></span>
                </div>
                <hr>
                <div class="featured-content-list">
                   <button type="button" data-name="Huawei Watch Buds" data-price="4059" class="default-btn border-radius-5">Add to cart</button>
                </div>
             </div>
          </div>
       </div>
       
       <!-- This is a link to our JavaScript file -->
      <script src="js/script.js"></script> 
  </body>
</html>


VIEWING PRODUCTS IN OUR SHOPPING CART

<div class="modal fade" id="staticBackdrop" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
     <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
           <div class="modal-header">
              <h5 class="modal-title" id="staticBackdropLabel">Your Cart</h5>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">x</button>
           </div>
           <div class="modal-body">
              <table class="show-cart table"></table><!-- Display the products -->
              <div class="grand-total">Total price: $<span class="total-cart"></span></div><!-- Display the total price -->
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
              <button type="button" class="clear-cart btn btn-danger">Clear All</button>
            </div>
        </div>
     </div>
    </div>


BASIC javaScript FUNCTIONS

/*
Broght to you by Vasplus Programming Blog
*/
var shoppingCart = function () {

  cart = [];
  // Get Items
  function Item(name, price, count) 
  {
	this.name = name;
	this.price = price;
	this.count = count;
  }

  // Save cart
  function saveCart() {
    localStorage.setItem('shoppingCart', JSON.stringify(cart));  }

  // Load cart
  function loadCart() {
    cart = JSON.parse(localStorage.getItem('shoppingCart'));
  }
  if (localStorage.getItem("shoppingCart") != null) {
    loadCart();
  }


  var obj = {};

  // Add to cart
  obj.addItemToCart = function (name, price, count) {
    for (var item in cart) {
      if (cart[item].name === name) {
        cart[item].count++;
        saveCart();
        return;
      }
    }
    var item = new Item(name, price, count);
    cart.push(item);
    saveCart();
  };
  // Set count from item
  obj.setCountForItem = function (name, count) 
  {
    for (var i in cart) 
	{
      if (cart[i].name === name) 
	  {
        cart[i].count = count;
        break;
      }
    }
	saveCart();
  };
  // Remove item from cart
  obj.removeItemFromCart = function (name) {
    for (var item in cart) {
      if (cart[item].name === name) {
        cart[item].count--;
        if (cart[item].count === 0) {
          cart.splice(item, 1);
        }
        break;
      }
    }
    saveCart();
  };

  // Remove all items from cart
  obj.removeItemFromCartAll = function (name) {
    for (var item in cart) {
      if (cart[item].name === name) {
        cart.splice(item, 1);
        break;
      }
    }
    saveCart();
  };

  // Clear cart
  obj.clearCart = function () {
    cart = [];
    saveCart();
  };

  // Count cart 
  obj.totalCount = function () {
    var totalCount = 0;
    for (var item in cart) {
      totalCount += cart[item].count;
    }
    return totalCount;
  };

  // Total cart
  obj.totalCart = function () {
    var totalCart = 0;
    for (var item in cart) {
      totalCart += cart[item].price * cart[item].count;
    }
    return Number(totalCart.toFixed(2));
  };

  // List cart
  obj.listCart = function () {
    var cartCopy = [];
    for (i in cart) {
      item = cart[i];
      itemCopy = {};
      for (p in item) {
        itemCopy[p] = item[p];
      }
      itemCopy.total = Number(item.price * item.count).toFixed(2);
      cartCopy.push(itemCopy);
    }
    return cartCopy;
  };
  return obj;
}();


Conclusion

By using basic arrays and functions, you can build a fully functional shopping cart system that can add, update, remove, and calculate the total of items and their cost in your shopping cart.
The awesome part of this tutorial is that it uses a localStorage to temporarily store data at the client side without having to directly store them in a final database at the server side.

Please download the zipped file to get the complete source code of the Shopping Cart system

Post Comment
Press Enter to send
No comment yet.

Submit your Job or Project Today!

We can help you turn your idea into reality, take over your existing project, or extend your current development team.

Submit your idea job or project below and we will follow up with you shortly.

OUR OBJECTIVE

Our objective is to reach a place where our services will be highly regarded by businesses from various industrial domains for building their innovative busines solutions with our cutting-edge technological expertise, interactive designs and uncompromised quality.

OUR MISSION

We aspire to help businesses ranging from startups to enterprises, who reach out to us with their requirements, in achieving great lengths, expanding their reach, upscaling their products, and generate a large user-base with our outstanding and cost-effective services.

Please Wait....
Please Wait...