Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active August 23, 2023 07:00
Show Gist options
  • Save code-boxx/b4b39ebd038489ff5554b679ac54b4e0 to your computer and use it in GitHub Desktop.
Save code-boxx/b4b39ebd038489ff5554b679ac54b4e0 to your computer and use it in GitHub Desktop.
Javascript Shopping Cart

JAVASCRIPT SHOPPING CART

https://code-boxx.com/simple-vanilla-javascript-shopping-cart/

IMAGES

JS-CART-1 JS-CART-2

NOTES

  1. Edit products.js, fill in your own products.
  2. Create an images folder, put all images inside.
  3. Access cart.html in the browser, use http:// not file://.
  4. Set iURL in cart.js section A to absolute URL if you have trouble with the images.
  5. Lastly, remember to complete your own checkout sequence in cart.js, section H.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

/* (A) ENTIRE PAGE */
#cart-wrap * {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
#cart-wrap {
max-width: 800px;
margin: 0 auto;
}
input.cart, button.cart {
border: 0;
padding: 10px;
color: #fff;
background: #d32828;
cursor: pointer;
}
/* (B) PRODUCTS */
#cart-products {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-gap: 10px; padding: 10px;
}
.p-item { position: relative; }
.p-img { width: 100%; }
.p-info {
display: flex; align-items: center;
position: absolute;
bottom: 0; left: 0;
width: 100%; padding: 10px;
background: rgba(0, 0, 0, 0.5);
}
.p-txt { flex-grow: 1; }
.p-name {
color: #fff;
font-size: 1.1em; font-weight: 700;
}
.p-price { color: #fff; }
.p-add { font-size: 1.5em; }
/* (C) CART */
#cart-items { padding: 10px; }
.c-item {
padding: 10px;
display: flex;
align-items: center;
background: #f2f2f2;
}
.c-item:nth-child(even) { background: #fff; }
.c-qty {
width: 60px;
padding: 10px;
}
.c-name {
padding: 0 10px;
flex-grow: 1;
}
.c-del { font-size: 1.2em; }
.c-total {
padding: 10px;
font-size: 1em; font-weight: 700;
background: #ffe9e9;
}
.c-go { margin-top: 10px; }
<!DOCTYPE html>
<html>
<head>
<title>Simple JS Cart</title>
<meta charset="utf-8">
<link rel="stylesheet" href="cart.css">
<script src="products.js"></script>
<script src="cart.js"></script>
</head>
<body>
<!-- (A) CART -->
<div id="cart-wrap">
<!-- (A1) PRODUCTS LIST -->
<div id="cart-products"></div>
<!-- (A2) CURRENT CART ITEMS -->
<div id="cart-items"></div>
</div>
<!-- (B) TEMPLATES -->
<!-- (B1) PRODUCT CELL -->
<template id="template-product">
<div class="p-item">
<img class="p-img">
<div class="p-info">
<div class="p-txt">
<div class="p-name"></div>
<div class="p-price"></div>
</div>
<button class="cart p-add">+</button>
</div>
</div>
</template>
<!-- (B2) CART ITEMS -->
<template id="template-cart">
<div class="c-item">
<input class="c-qty" type="number" min="0">
<div class="c-name"></div>
<button class="c-del cart">X</button>
</div>
</template>
<template id="template-cart-checkout">
<div class="c-go">
<button class="c-empty cart" onclick="cart.nuke()">Empty</button>
<button class="c-checkout cart" onclick="cart.checkout()">Checkout</button>
</div>
</template>
</body>
</html>
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
currency : "$", // currency symbol
total : 0, // total amount
// (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) EMPTY ENTIRE CART
nuke : () => { if (confirm("Empty cart?")) {
cart.items = {};
localStorage.removeItem("cart");
cart.list();
}},
// (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 template = document.getElementById("template-product").content, p, item;
for (let id in products) {
p = products[id];
item = template.cloneNode(true);
item.querySelector(".p-img").src = cart.iURL + p.img;
item.querySelector(".p-name").textContent = p.name;
item.querySelector(".p-price").textContent = cart.currency + p.price.toFixed(2);
item.querySelector(".p-add").onclick = () => cart.add(id);
cart.hPdt.appendChild(item);
}
// (C3) LOAD CART FROM PREVIOUS SESSION
cart.load();
// (C4) LIST CURRENT CART ITEMS
cart.list();
},
// (D) LIST CURRENT CART ITEMS (IN HTML)
list : () => {
// (D1) RESET
cart.total = 0;
cart.hItems.innerHTML = "";
let item, 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 template = document.getElementById("template-cart").content, p;
for (let id in cart.items) {
p = products[id];
item = template.cloneNode(true);
item.querySelector(".c-del").onclick = () => cart.remove(id);
item.querySelector(".c-name").textContent = p.name;
item.querySelector(".c-qty").value = cart.items[id];
item.querySelector(".c-qty").onchange = function () { cart.change(id, this.value); };
cart.hItems.appendChild(item);
cart.total += cart.items[id] * p.price;
}
// (D3-3) TOTAL AMOUNT
item = document.createElement("div");
item.className = "c-total";
item.id = "c-total";
item.innerHTML = `TOTAL: ${cart.currency}${cart.total}`;
cart.hItems.appendChild(item);
// (D3-4) EMPTY & CHECKOUT
item = document.getElementById("template-cart-checkout").content.cloneNode(true);
cart.hItems.appendChild(item);
}
},
// (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;
cart.total = 0;
for (let id in cart.items) {
cart.total += cart.items[id] * products[id].price;
document.getElementById("c-total").innerHTML = `TOTAL: ${cart.currency}${cart.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));
data.append("total", cart.total);
fetch("SERVER-SCRIPT", { method:"POST", body:data })
.then(res=>res.text())
.then(res => console.log(res))
.catch(err => console.error(err));
*/
}
};
window.addEventListener("DOMContentLoaded", cart.init);
// DUMMY PRODUCTS (PRODUCT ID : DATA)
var products = {
123: {
name : "iPon Min",
img : "JS-CART-1.png",
price : 123
},
124: {
name : "iPon Pro Max Plus",
img : "JS-CART-2.png",
price : 1234
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment