Simple Javascript Shopping Cart – Free Code Download

Welcome to a tutorial on how to create a simple vanilla Javascript Shopping Cart. Looking to build an eCommerce website or web app? Not too keen on the complicated bloated scripts and just need a simple interface? Well, here it is. A standalone local storage shopping cart that does not use any frameworks – Read on to find out!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

TABLE OF CONTENTS

Download & Demo How It Works Useful Bits & Links
The End

 

 

DOWNLOAD & DEMO

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

JAVASCRIPT CART DEMO

 

QUICKSTART

For you guys who just want to use this as a “plugin”:

  • Edit products.js, fill in your own products.
  • Put the product images in the images/ folder.
  • Launch cart.html, use http:// not file://.
  • Lastly, complete your own checkout sequence cart.js, section H.

 

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

HOW IT WORKS

All right, let us now get into the mechanics of the shopping cart itself.

 

1) THE HTML

cart.html
<!-- (A) CSS + JS -->
<link rel="stylesheet" href="cart.css">
<script src="products.js"></script>
<script src="cart.js"></script>
 
<div id="cart-wrap">
  <!-- (B) PRODUCTS LIST -->
  <div id="cart-products"></div>
 
  <!-- (C) CURRENT CART -->
  <div id="cart-items"></div>
</div>

This should be very straightforward with only 2 sections in the <div id="cart-wrap"> container:

  • <div id="cart-products"> To contain the list of products.
  • <div id="cart-items"> To show the current items in the cart.

 

 

2) THE PRODUCTS

products.js
// DUMMY PRODUCTS (PRODUCT ID : DATA)
var products = {
  123: {
    name : "MokBook Thicc",
    desc : "Greatest properly off ham exercise all.",
    img : "dummy-pdt-b.jpg",
    price : 2034
  },
  124: {
    name : "MokBook Rookie",
    desc : "Unsatiable its possession nor off.",
    img : "dummy-pdt-b.jpg",
    price : 1247
  },
  125: {
    name : "iPong Max",
    desc : "All difficulty unreserved the solicitude.",
    img : "dummy-pdt-a.jpg",
    price : 675
  },
  126: {
    name : "iTab Pok",
    desc : "Had judgment out property the supplied. ",
    img : "dummy-pdt-a.jpg",
    price : 842
  }
};

Since we do not have a database here, the only option is to hardcode all the products in a script.

 

3) THE JAVASCRIPT

3A) THE PROPERTIES

cart.js
var cart = {
  // (A) PROPERTIES
  hPdt : null, // HTML products list
  hItems : null, // HTML current cart
  items : {} // Current items in cart
};

Captain Obvious – The var cart object will keep all the cart related mechanics. Right at the top, we only have 3 properties.

  • cart.hPdt and cart.hItems shouldn’t be too difficult to understand – We will use these to refer to <div id="cart-products"> and <div id="cart-items">.
  • cart.items contains the current items in the cart. This is simply an object that has the format of PRODUCT ID : QUANTITY.

 

 

3B) WORKING WITH LOCALSTORAGE

cart.js
var cart = {
  // (B) LOCALSTORAGE CART
  // (B1) SAVE CURRENT CART INTO LOCALSTORAGE
  save : function () {
    localStorage.setItem("cart", JSON.stringify(cart.items));
  },

  // (B2) LOAD CART FROM LOCALSTORAGE
  load : function () {
    cart.items = localStorage.getItem("cart");
    if (cart.items == null) { cart.items = {}; }
    else { cart.items = JSON.parse(cart.items); }
  },
  
  // (B3) NUKE CART!
  nuke : function () {
    if (confirm("Empty cart?")) {
      cart.items = {};
      localStorage.removeItem("cart");
      cart.list();
    }
  }
};

That’s right. Without a server session, whatever is in the cart will disappear as soon as the user reloads the page. To prevent that from happening, we will save the cart items into the localStorage.

  • cart.save() simply saves cart.items into the local storage.
  • cart.load() will fetch the data from the local storage and restore cart.items.
  • Lastly, cart.nuke() will empty the entire cart.

 

3C) SHOPPING CART INITIALIZATION

cart.js
var cart = {
  // (C) INITIALIZE
  init : function () {
    // (C1) GET HTML ELEMENTS
    cart.hPdt = document.getElementById("cart-products");
    cart.hItems = document.getElementById("cart-items");
    
    // (C2) DRAW PRODUCTS LIST
    cart.hPdt.innerHTML = "";
    let p, item, part;
    for (let id in cart.products) {
      // WRAPPER
      p = cart.products[id];
      item = document.createElement("div");
      item.className = "p-item";
      cart.hPdt.appendChild(item);

      // PRODUCT IMAGE
      part = document.createElement("img");
      part.src = p.img;
      part.className = "p-img";
      item.appendChild(part);

      // PRODUCT NAME
      part = document.createElement("div");
      part.innerHTML = p.name;
      part.className = "p-name";
      item.appendChild(part);
      
      // PRODUCT PRICE
      part = document.createElement("div");
      part.innerHTML = "$" + p.price;
      part.className = "p-desc";
      item.appendChild(part);
      
      // PRODUCT DESCRIPTION
      part = document.createElement("div");
      part.innerHTML = p.desc;
      part.className = "p-price";
      item.appendChild(part);

      // ADD TO CART
      part = document.createElement("input");
      part.type = "button";
      part.value = "Add to Cart";
      part.className = "cart p-add";
      part.onclick = cart.add;
      part.dataset.id = id;
      item.appendChild(part);
    }
    
    // (C3) LOAD CART FROM PREVIOUS SESSION
    cart.load();
    
    // (C4) LIST CURRENT CART ITEMS
    cart.list();
  }
};

The init() function runs on page load. It may seem to be massive, but what it does is actually very basic:

  • C1 – “Tie” cart.hPdt to <div id="cart-products"> and cart.hItems to <div id="cart-items">.
  • C2 – Draw the list of products.
  • C3 – Load the cart from the previous session.
  • C4 – Draw the current cart items.

 

 

3D) DRAW SHOPPING CART ITEMS

cart.js
var cart = {
  // (D) LIST CURRENT CART ITEMS (IN HTML)
  list : function () {
    // (D1) RESET
    cart.hItems.innerHTML = "";
    let item, part, pdt;
    let empty = true;
    for (let key in cart.items) {
      if(cart.items.hasOwnProperty(key)) { empty = false; break; }
    }

    // (D2) CART IS EMPTY
    if (empty) {
      item = document.createElement("div");
      item.innerHTML = "Cart is empty";
      cart.hItems.appendChild(item);
    }
    
    // (D3) CART IS NOT EMPTY - LIST ITEMS
    else {
      let p, total = 0, subtotal = 0;
      for (let id in cart.items) {
        // ITEM
        p = cart.products[id];
        item = document.createElement("div");
        item.className = "c-item";
        cart.hItems.appendChild(item);
 
        // NAME
        part = document.createElement("span");
        part.innerHTML = p.name;
        part.className = "c-name";
        item.appendChild(part);
 
        // REMOVE
        part = document.createElement("input");
        part.type = "button";
        part.value = "X";
        part.dataset.id = id;
        part.className = "c-del cart";
        part.addEventListener("click", cart.remove);
        item.appendChild(part);

        // QUANTITY
        part = document.createElement("input");
        part.type = "number";
        part.value = cart.items[id];
        part.dataset.id = id;
        part.className = "c-qty";
        part.addEventListener("change", cart.change);
        item.appendChild(part);
 
        // SUBTOTAL
        subtotal = cart.items[id] * p.price;
        total += subtotal;
      }

      // EMPTY BUTTONS
      item = document.createElement("input");
      item.type = "button";
      item.value = "Empty";
      item.addEventListener("click", cart.nuke);
      item.classList.add("c-empty");
      cart.hItems.appendChild(item);

      // CHECKOUT BUTTONS
      item = document.createElement("input");
      item.type = "button";
      item.value = "Checkout - " + "$" + total;
      item.addEventListener("click", cart.checkout);
      item.classList.add("c-checkout");
      cart.hItems.appendChild(item);
    }
  }
});

The list() function draws the current cart items into <div id="cart-items">. Looks complicated, but it is just generating a whole load of HTML.

 

3E) SHOPPING CART ACTIONS

cart.js
var cart = {
  // (E) ADD ITEM INTO CART
  add : function () {
    if (cart.items[this.dataset.id] == undefined) {
      cart.items[this.dataset.id] = 1;
    } else {
      cart.items[this.dataset.id]++;
    }
    cart.save();
    cart.list();
  },

  // (F) CHANGE QUANTITY
  change : function () {
    if (this.value == 0) {
      delete cart.items[this.dataset.id];
    } else {
      cart.items[this.dataset.id] = this.value;
    }
    cart.save();
    cart.list();
  },
  
  // (G) REMOVE ITEM FROM CART
  remove : function () {
    delete cart.items[this.dataset.id];
    cart.save();
    cart.list();
  },
  
  // (H) CHECKOUT
  checkout : function () {
    // SEND DATA TO SERVER
    // CHECKS
    // SEND AN EMAIL
    // RECORD TO DATABASE
    // PAYMENT
    // WHATEVER IS REQUIRED
    alert("TO DO");

    /*
    var data = new FormData();
    data.append('cart', JSON.stringify(cart.items));
    data.append('products', JSON.stringify(cart.products));
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "SERVER-SCRIPT");
    xhr.onload = function(){ ... };
    xhr.send(data);
    */
  }
});

Finally, all of these functions deal with cart actions:

  • cart.add() Adds a selected item into the cart. Remember the format of cart.items = { ID : QUANTITY }? That is exactly what we are doing here.
  • cart.change() Changes the quantity of the item in the cart.
  • cart.remove() Removes an item from the cart.
  • cart.checkout() Is up to you to complete.

 

 

4) THE CSS

cart.css
/* (A) ENTIRE PAGE */
#cart-wrap {
  font-family: arial, sans-serif;
  display: grid;
  grid-template-columns: 70% 30%;
  margin: 0 auto;
  max-width: 1000px;
}
input.cart, button.cart {
  font-weight: bold;
  font-size: 1em;
  padding: 10px; 
  border: none;
  color: #fff;
  background: #d64107;
  cursor: pointer;
}

/* (B) PRODUCTS LIST */
#cart-products {
  display: grid;
  grid-template-columns: auto auto;
  grid-gap: 10px;
  padding: 10px;
}
.p-item {
  padding: 10px;
  border: 1px solid #aaa;
  text-align: center;
}
.p-name {
  text-transform: uppercase;
  font-weight: bold;
  font-size: 1.1em;
}
.p-img { max-width: 180px; }
.p-desc {
  color: #777;
  font-size: 0.9em;
  line-height: 1.5em;
}
.p-price {
  font-weight: bold;
  font-size: 1.1em;
  margin: 10px 0;
}
input.p-add { width: 80%; }

/* (D) CURRENT SHOPPING CART */
#cart-items {
  padding: 10px;
  background: #f1f1f1;
}
.c-item {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
}
.c-name {
  width: 100%;
  font-size: 1.3em;
  line-height: 1.5em;
}
.c-del { width: 20%; }
.c-qty {
  width: 75%;
  font-size: 1em;
}
input.c-empty, input.c-checkout {
  width: 100%;
  margin-top: 10px;
}

/* (E) RESPONSIVE */
@media screen AND (max-width: 768px) {
  #cart-wrap { grid-template-columns: 60% 40%; }
  #cart-products { grid-template-columns: auto; }
}

Yep, just a whole load of cosmetics. Feel free to change these to your own, or discard them entirely – Use your own framework.

 

USEFUL BITS & LINKS

That’s all for this project, and here is a small section on some extras and links that may be useful to you.

 

LIMITATIONS & NOTES

  • The Javascript Cart requires the localstorage API to work properly. Most modern browsers will support that, but use Modernizr to check for browser compatibility and load a polyfill if you want. Links below.
  • Javascript and local storage can be easily messed with. You will want to do checks on the server-side upon checkout.

 

MULTIPLE PRODUCT CATEGORIES?

As you may have noticed, there are no product categories. But yes, it is possible to add sections with some changes:

  • Create another var categories object to hold the product IDs of each category. For example { CATEGORY-A: [123, 124, 125], CATEGORY-B: [1, 2, 3] }.
  • Modify the cart.draw() function to draw the products in a selected category.

 

A BETTER SHOPPING CART

Need a shopping cart with product options? Product categories? Discount coupons? User system and admin panel? Click here to check out my eBook! Go ahead, take a sneak peek inside - Click here to download the first 4 chapters.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

4 thoughts on “Simple Javascript Shopping Cart – Free Code Download”

  1. Hi, Thank you so much for this. I had been looking for a shopping cart html code that would work for over a month until i found yours yesterday. I’m just a beginner and want to be able to give options for Chips & drink. Also, if you don’t mind….how do i get the checkout button to do exactly that? Any help is appreciated.

  2. Peter Levenspiel

    Thanks for the script. IM trying to use it for a cafe website but I cant find a way to insert a subheading bewteen products. For example I need to put the heading hot drinks, then list 4 products. then cold drinks and then another 7 products and so on. I cannot see how this coudl be done. Any tips would be greatly appreciated.

    1. Basically, product categories. Not impossible, but quite a hassle.

      (HTML) Add more sections as required.
      <h1>HOT</h1> <div id="cart-hot"></div>
      <h1>COLD</h1> <div id="cart-cold"></div>

      (A) Split the products.
      var hot = { ... }; var cold = { ... };

      (B) Reshuffle this entire section into a reusable “draw” function.
      function draw (products, target) {
      var container = document.getElementById(target)...
      }

      Finally, just draw(hot, "cart-hot"); draw(cold, "cart-cold");.

Leave a Comment

Your email address will not be published. Required fields are marked *