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.

 

QUICK NOTES

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.
  • Set iURL in cart.js section A to an absolute URL if you have trouble with the images.
  • Launch cart.html, use http:// not file://.
  • Lastly, complete your own checkout sequence cart.js, section H.
If you spot a bug, feel free to comment below. I try to answer short 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.

 

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

 

 

HOW IT WORKS

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

 

PART 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.

 

PART 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 don’t have a database here, the only option is to hardcode all the products in a script.

 

 

PART 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
  iURL : "images/", // Product image URL folder
};

Captain Obvious – The var cart object will keep all the cart-related mechanics. Right at the top, we only have 4 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.
  • iURL is the URL to the product image folder.

 

3B) WORKING WITH LOCALSTORAGE

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

// (B2) LOAD CART FROM LOCALSTORAGE
load : () => {
  cart.items = localStorage.getItem("cart");
  if (cart.items == null) { cart.items = {}; }
  else { cart.items = JSON.parse(cart.items); }
},
  
// (B3) NUKE CART!
nuke : () => {
  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
// (C) INITIALIZE
init : () => {
  // (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(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
// (D) LIST CURRENT CART ITEMS (IN HTML)
list : () => {
  // (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.className = "c-del cart";
      part.onclick = () => { cart.remove(id); };
      item.appendChild(part);

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

    // TOTAL AMOUNT
    item = document.createElement("div");
    item.className = "c-total";
    item.id = "c-total";
    item.innerHTML ="TOTAL: $" + total;
    cart.hItems.appendChild(item);
 
    // EMPTY BUTTON
    item = document.createElement("input");
    item.type = "button";
    item.value = "Empty";
    item.onclick = cart.nuke;
    item.classList.add("c-empty");
    cart.hItems.appendChild(item);

    // CHECKOUT BUTTON
    item = document.createElement("input");
    item.type = "button";
    item.value = "Checkout";
    item.onclick = 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
// (E) ADD ITEM INTO CART
add : (id) => {
  if (cart.items[id] == undefined) { cart.items[id] = 1; }
  else { cart.items[id]++; }
  cart.save(); cart.list();
},

// (F) CHANGE QUANTITY
change : (pid, qty) => {
  // (F1) REMOVE ITEM
  if (qty <= 0) {
    delete cart.items[pid];
    cart.save(); cart.list();
  }

  // (F2) UPDATE TOTAL ONLY
  else {
    cart.items[pid] = qty;
    var total = 0;
    for (let id in cart.items) {
      total += cart.items[id] * products[id].price;
      document.getElementById("c-total").innerHTML ="TOTAL: $" + total;
    }
  }
},
  
// (G) REMOVE ITEM FROM CART
remove : (id) => {
  delete cart.items[id];
  cart.save();
  cart.list();
},
  
// (H) CHECKOUT
checkout : () => {
  // 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(products));
 
  fetch("SERVER-SCRIPT", { method:"POST", body:data })
  .then(res=>res.text()).then((res) => {
    console.log(res);
  })
  .catch((err) => { console.error(err); });
  */
}

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.

 

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.

 

COMPATIBILITY CHECKS

Works well in all modern browsers. If you want to be safe, use Modernizr to do feature checks and even load polyfills.

 

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!

 

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!

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

    1. How to separate “like a real webite” –

      1) Don’t skip the basics.
      2) Study basic HTML.
      3) Study basic CSS.
      4) Study responsive CSS.
      5) Study some web design and page layouts.
      6) Study basic Javascript.
      7) Don’t treat web development like “it’s as easy as plug-and-play”.
      8) Read the tutorial again after doing all of the above.

      Good luck.

  1. Hi there,
    Thank you so much for this! It really helps as your explanations are super clear.
    I’m having a little issue with the incrementation : can’t go above 2 or 3, it starts decreasing after this.
    Do you know why?

    1. I will assume that “cannot increment” refers to the quantity field, that is a <input type="number">. An interesting bug that only happens on Chromium-based browsers –

      1) Create the number fields.
      2) Increment and change quantity.
      3) Remove and regenerate the number fields.
      4) The next click will register as a decrement.

      This is something that we cannot fix, I have only “bypassed” the problem. Report to Google if you want – https://support.google.com/chrome/answer/95315?hl=en&co=GENIE.Platform%3DDesktop

  2. Hi, thank you very much!
    This is what i am looking for. I’m beginner of Google App Script. I already deploy it well. Please help to teach me how to save the cart to a sheet of GG spreadsheet. Any help is appreciated.

  3. Thank you very much for this!

    If I use my paypal for checkout, how do I integrate this ?

    Thank you
    Rally

  4. 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.

  5. 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 *