Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <!-- (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>

<!-- (X) VISIT CODE-BOXX -->
<div id="code-boxx">
  Visit
  <a href="https://code-boxx.com/simple-vanilla-javascript-shopping-cart/"
     target="_blank">
    Code Boxx
  </a> for more details.
</div>
              
            
!

CSS

              
                /* (A) ENTIRE PAGE */
#cart-wrap *, #code-boxx {
  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%;
  max-height: 400px;
  object-fit: cover;
}
.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; }

/* (X) NOT IMPORTANT - FOOTER */
#code-boxx {
  padding: 10px;
  margin-bottom: 20px;
  background: #fea;
  text-align: center;
  font-weight: 600;
  margin-top: 50px;
}
#code-boxx a {
  display: inline-block;
  padding: 5px;
  text-decoration: none;
  background: #b90a0a;
  color: #fff;
}
              
            
!

JS

              
                // DUMMY PRODUCTS (PRODUCT ID : DATA)
var products = {
  123: {
    name : "iPon Min",
    img : "https://images.unsplash.com/photo-1529088148495-2d9f231db829?crop=entropy&cs=tinysrgb&fm=jpg&ixid=MnwzMjM4NDZ8MHwxfHJhbmRvbXx8fHx8fHx8fDE2NzI4NDAyMzM&ixlib=rb-4.0.3&q=80",
    price : 123
  },
  124: {
    name : "iPon Pro Max Plus",
    img : "https://images.unsplash.com/photo-1634403665481-74948d815f03?crop=entropy&cs=tinysrgb&fm=jpg&ixid=MnwzMjM4NDZ8MHwxfHJhbmRvbXx8fHx8fHx8fDE2NzI4NDAyNTk&ixlib=rb-4.0.3&q=80",
    price : 1234
  }
};

var cart = {
  // (A) PROPERTIES
  hPdt : null,      // html products list
  hItems : null,    // html current cart
  items : {},       // current items in cart
  iURL : "",        // 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);
              
            
!
999px

Console