Shopping Cart JavaScript complete tutorial

Welcome to my Blog, In this article, we will build the shopping cart javascript complete tutorial with source code firstly we discuss what is the working of shopping cart javascript means how to play with it. Its a cool UI design when you hover on any card then the card expand and show the product description and price with add button when you click on add button now you see the quantity you can increase or decrease the quantity of the product and if you like any product now you add in the favorite list when clicking on the heart icon.

when you add products in the cart go to the cart icon and view the brief description of each product here you can increase or decrease the product quantity and delete specific product after bottom of the page you can see clear cart or purchase buttons the clear cart button clear the cart products and purchase go to forward and see order now or cancel when you click on order now then your order has been placed and in that current location popup you can see order id or total payment amount are available it’s a complete working of Shopping cart Javascript.

Shopping cart JavaScript images download

Shopping cart javascript complete tutorial Video Link :
shopping cart JavaScript

if you want to watch more videos go to YouTube channel

So in the HTML have a some cdn’s and link a style and script file and has a app id of main div.

<!DOCTYPE html>
<html lang="en" >
<head>
	<meta charset="UTF-8">
	<title>Shopping Cart JS</title>
	<meta name="viewport" content="width=device-width, initial-scale=1"><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
	<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.0-2/css/all.min.css'>
	<link rel="stylesheet" href="./style.css">
</head>
<body>
	<div id='app'></div>
	<script  src="./script.js"></script>
</body>
</html>

Shopping cart javascript Complete tutorial ( CSS ) :

now we working on shopping cart styling firstly we import a google font API and design the root and set the margin and padding of the shopping cart javascript and design the static data of the page the mainly is products cards and after that make the design of the box area li each child and now make a keyframe animation of the page background and style the icons, cart quantity buttons, hover effects, card, stocks or outofstockes text, top of the cards, card details, products name, etc.

@import url("https://fonts.googleapis.com/css2?family=Montserrat&display=swap");
:root {
font-size: 16px;
color: white;
font-family: "Montserrat", sans-serif;
}

* {
margin: 0;
padding: 0;
box-sizing: border-box;
}

div {
display: flex;
}

button {
border: none;
background: none;
outline: none;
color: white;
cursor: pointer;
transition: 0.5s;
}

.banner {
position: relative;
height: 100vh;
width: 100vw;
background: linear-gradient(to left, #8942a8, #ba382f);
overflow: hidden;
}
.banner .stock-limit {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
border-radius: 20px;
background-color: #010101;
width: 400px;
height: 180px;
flex-direction: column;
display: none;
}
.banner .stock-limit em {
position: absolute;
width: 80%;
top: 20%;
left: 0;
right: 0;
margin: 0 auto;
line-height: 1.5rem;
text-align: center;
font-weight: 600;
font-size: 1.2rem;
}

.banner .cover {
position: absolute;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.75);
-webkit-backdrop-filter: blur(5px);
backdrop-filter: blur(5px);
display: none;
}

.box-area {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow: hidden;
}

.box-area li {
position: absolute;
display: block;
list-style: none;
width: 25px;
height: 25px;
background: white;
overflow: hidden;
-webkit-animation: animation 20s linear infinite;
animation: animate 20s linear infinite;
bottom: -120px;
}

.box-area li:nth-child(1) {
left: 86%;
width: 80px;
height: 80px;
-webkit-animation-delay: 0s;
animation-delay: 0s;
}

.box-area li:nth-child(2) {
left: 12%;
width: 30px;
height: 30px;
-webkit-animation-delay: 1.5s;
animation-delay: 1.5s;
-webkit-animation-duration: 10s;
animation-duration: 10s;
}

.box-area li:nth-child(3) {
left: 70%;
width: 100px;
height: 100px;
-webkit-animation-delay: 5.5s;
animation-delay: 5.5s;
}

.box-area li:nth-child(4) {
left: 42%;
width: 150px;
height: 150px;
-webkit-animation-delay: 0s;
animation-delay: 0s;
-webkit-animation-duration: 15s;
animation-duration: 15s;
}

.box-area li:nth-child(5) {
left: 65%;
width: 40px;
height: 40px;
-webkit-animation-delay: 0s;
animation-delay: 0s;
}

.box-area li:nth-child(6) {
left: 15%;
width: 110px;
height: 110px;
-webkit-animation-delay: 3.5s;
animation-delay: 3.5s;
-webkit-animation-duration: 15s;
animation-duration: 15s;
}

@-webkit-keyframes animate {
0% {
transform: translateY(0) rotate(0deg);
opacity: 1;
}
100% {
transform: translateY(-100vh) rotate(360deg);
opacity: 0;
}
}
@keyframes animate {
0% {
transform: translateY(0) rotate(0deg);
opacity: 1;
}
100% {
transform: translateY(-100vh) rotate(360deg);
opacity: 0;
}
}
.fa-shopping-cart {
position: absolute;
right: 2rem;
top: 1.2rem;
color: black;
}

.fa-shopping-cart:hover {
color: white;
}

.total-qty {
position: absolute;
height: 1rem;
width: 1rem;
background: white;
color: black;
border-radius: 50%;
border: 1px solid white;
text-align: center;
line-height: 1rem;
font-weight: 600;
top: 1rem;
right: 1.5rem;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

.main-cart {
position: absolute;
justify-content: space-evenly;
flex-wrap: wrap;
width: 90%;
height: 100%;
margin-left: 5%;
align-self: center;
align-items: center;
}

.card {
position: relative;
flex-shrink: 0;
height: 300px;
width: 200px;
background-color: #010101;
border-radius: 20px;
overflow: hidden;
box-shadow: 0 7px 5px -5px #4d4b4b;
transition: 0.5s;
}
.card .img-container {
position: absolute;
height: 185px;
width: 185px;
margin: 0 auto;
left: 0;
right: 0;
transform: translateY(35px);
}
.card .img-container img {
width: 100%;
align-self: center;
}
.card .img-container .out-of-stock-cover {
position: absolute;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.25);
justify-content: center;
align-items: center;
display: none;
}
.card .img-container .out-of-stock-cover span {
font-weight: 900;
color: rgba(255, 200, 200, 0.75);
font-size: 1.5rem;
}

.top-bar {
transform: translateY(0.5rem);
width: 100%;
justify-content: space-between;
align-items: baseline;
padding: 0 1rem;
}
.top-bar .fa-apple {
font-size: 1.5rem;
}
.top-bar .stocks {
font-size: 0.8rem;
color: lightgreen;
}

.card .details {
position: absolute;
height: 220px;
width: 100%;
background-color: #2e2f33;
border-radius: 20px;
flex-direction: column;
justify-content: space-between;
padding: 20px;
bottom: -165px;
transition: 0.25s;
}

.card .details .name-fav {
justify-content: space-between;
}

.card .details .name-fav strong {
font-weight: 600;
}

.fav {
color: red;
}

.card .details .wrapper {
flex-direction: column;
justify-content: space-between;
transform: translateY(5px);
display: none;
}

.details .wrapper p {
font-size: 0.9rem;
padding: 5px 0;
font-weight: light;
}

so shopping cart javascript front page design completed now working on sidebar styling. when you add some products to the cart then you go to the cart right there have cart products and purchase or cancel button. firstly we set the purchase button font size, alignment, color, or hover effect with style the sidebar and all elements that exist in the sidebar. you can directly copy the complete source code and paste it into your styling file.

.card .details .purchase {
width: 100%;
justify-content: space-between;
align-items: center;
}

.card .details .purchase p {
font-weight: 500;
}

.details .purchase .add-btn {
border-radius: 20px;
border: 1px solid white;
background: none;
color: white;
padding: 6px 10px;
}

.details .purchase .add-btn:hover {
background: white;
color: black;
}

.main-cart .card:hover {
height: 450px;
width: 260px;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
}

.main-cart .card:hover .details {
bottom: 0;
}

.main-cart .card:hover .wrapper {
display: block;
}

.side-nav {
position: absolute;
background: #010101;
opacity: 0.95;
height: 100%;
width: 60%;
flex-direction: column;
top: 0;
right: -100%;
z-index: 10;
overflow: hidden;
transition: 0.5s;
}

.side-nav .fa-times {
position: absolute;
top: 20px;
right: 30px;
font-size: 1.5rem;
}

.side-nav h2 {
align-self: center;
transform: translateY(1rem);
font-size: 2rem;
font-weight: 600;
}

.side-nav .cart-items {
position: absolute;
width: 90%;
margin: 0 5%;
height: 50%;
top: 10%;
flex-direction: column;
}
.side-nav .cart-items .empty-cart {
margin: auto 0;
font-size: 2rem;
font-weight: 900;
text-align: center;
color: rgba(255, 255, 255, 0.25);
}

.side-nav .cart-items .cart-item {
height: 5rem;
width: 100%;
align-items: center;
justify-content: space-around;
border-bottom: 1px solid whitesmoke;
}
.side-nav .cart-items .cart-item:hover {
background: rgba(255, 255, 255, 0.25);
}
.side-nav .cart-items .cart-item .cart-img {
width: 5rem;
height: 5rem;
justify-content: center;
}
.side-nav .cart-items .cart-item .cart-img img {
width: 100%;
align-self: center;
}

.side-nav .final {
position: absolute;
align-self: flex-end;
flex-direction: column;
bottom: 10%;
}

.side-nav .final strong {
align-self: flex-end;
font-size: 1.2rem;
font-weight: 600;
margin-right: 20px;
margin-bottom: 1rem;
}

.side-nav .final .action {
justify-content: space-evenly;
}

.side-nav .final .action .btn {
font-size: 1.2rem;
padding: 1rem 2rem;
border: 1px solid white;
margin-right: 20px;
border-radius: 10px;
}

.side-nav .final .action .btn:hover {
color: black;
box-shadow: inset 20em 0 0 0 white;
}

when you complete the order and click purchase button then you cart summary comes in invoice popup how much products you buy or total price and after that add some media queries for content responsiveness.

.qty-change {
justify-content: space-evenly;
align-items: baseline;
}

.btn-qty {
border: 1px solid white;
border-radius: 50%;
padding: 2px 5px;
}
.btn-qty:hover {
background: white;
color: black;
}

.qty {
padding: 2px 5px;
}

.invoice {
position: absolute;
height: 90%;
width: 90%;
background: rgba(0, 0, 0, 0.95);
padding: 5% 4%;
margin: 0 auto;
left: 0;
right: 0;
align-self: center;
flex-direction: column;
border-radius: 20px;
transition: 0.25s;
}
.invoice .shipping-items {
padding: 10px 0;
width: 100%;
justify-content: space-between;
}
.invoice .shipping-items .item-names,
.invoice .shipping-items .items-price {
flex-direction: column;
justify-content: space-around;
}
.invoice .payment {
flex-direction: column;
}
.invoice .payment em,
.invoice .payment div {
margin-top: 10px;
font-weight: 600;
justify-content: space-between;
}
.invoice .order {
position: absolute;
bottom: 10%;
width: 40%;
justify-content: space-around;
}
.invoice .order .btn {
padding: 1rem 2rem;
border-radius: 10px;
font-size: 1.2rem;
}
.invoice .order .btn-order {
background: #00bbf9;
}
.invoice .order .btn-cancel {
background: #bb342f;
}
.invoice .order-details {
height: 300px;
flex-direction: column;
justify-content: space-around;
}
.invoice .order-details em,
.invoice .order-details p {
border-bottom: 1px dashed white;
padding-bottom: 10px;
}
.invoice .order-details em {
font-size: 1.2rem;
font-weight: 600;
}
.invoice .order-details .thanks {
position: absolute;
text-align: center;
margin: auto;
border: none;
left: 0;
right: 0;
bottom: 55%;
}
.invoice .order-details p {
font-size: 1.1rem;
}
.invoice .order-details p span {
font-weight: 600;
}

.btn-ok {
position: absolute;
width: 80%;
font-size: 1.2rem;
border-radius: 10px;
padding: 1rem 2rem;
margin: auto;
bottom: 10%;
left: 0;
right: 0;
background: #5bc0be;
}

@media (max-width: 768px) {
.side-nav {
width: 80%;
}

.invoice .order {
width: 60%;
}

.main-cart {
overflow: scroll;
}
}
@media (max-width: 576px) {
.side-nav {
width: 100%;
}
.side-nav .cart-img {
display: none;
}

.invoice .order {
width: 80%;
}

.nav {
width: 576px;
height: 4rem;
background: rgba(255, 255, 255, 0.5);
-webkit-backdrop-filter: blur(5px);
backdrop-filter: blur(5px);
filter: invert(1);
}

.main-cart {
justify-content: flex-start;
flex-wrap: nowrap;
flex-direction: column;
height: 95%;
top: 4rem;
}
.main-cart .card {
margin: 20px auto;
}
}

Read More : Hangman Game in JavaScript

Read More : Card Matching Game in JavaScript

Read More : Clock Train in JavaScript

Read More : Memory Card Game in JavaScript

Shopping cart javascript Complete tutorial ( JS ) :

Now here we discuss about each function that we have use in the script file.

we take product details array and each product take some attributes name ,price,image URL,quantity,heading,description.

const productDetails = [
{
  name: "Airpods Pro",
  price: 24900,
  imageUrl:
  "1.jpeg",
  qty: 10,
  heading: "Wireless Noise Cancelling Earphones",
  des:
  "AirPods Pro have been designed to deliver active Noise Cancellation for immersive sound. Transparancy mode so much can hear your surroundings." },

{
  name: "Apple Watch",
  price: 40900,
  imageUrl: "2.png",
  qty: 15,
  heading: "You’ve never seen a watch like this",
  des:
  "The most advanced Apple Watch yet, featuring the Always-On Retina display, the ECG app, international emergency calling, fall detection and a built‑in compass." },

{
  name: "Macbook Pro",
  price: 199900,
  imageUrl: "3.png",
  qty: 20,
  heading: "The best for the brightest",
  des:
  "Designed for those who defy limits and change the world, the new MacBook Pro is by far the most powerful notebook we’ve ever made. it’s the ultimate pro notebook for the ultimate user." },

{
  name: "iPhone 11 pro",
  price: 106600,
  imageUrl:
  "4.png",
  qty: 35,
  heading: "Pro cameras. Pro display. Pro performance",
  des:
  "A mind‑blowing chip that doubles down on machine learning and pushes the boundaries of what a smartphone can do. Welcome to the first iPhone powerful enough to be called Pro." },

{
  name: "iPad Pro",
  price: 71900,
  imageUrl:
  "5.png",
  qty: 25,
  heading: "Your next computer is not a computer",
  des:
  "It’s a magical piece of glass. It’s so fast most PC laptops can’t catch up. And you can use it with touch, pencil, keyboard and now trackpad. It’s the new iPad Pro." }];
  const cartDetails = [];

let talk about the addItem function when you click on the product add button now hide this button and show the quantity of product user can increase or decrease the quantity of the current product according to your requirement. after that we get the current product name, price, image or quantity and pass to the CartItems function then-current product add-in card details empty array that we have declared before after call render cart or cart item total function these functions discuss later.

function addItem(event) {
  let btnClicked =
  event.parentElement.parentElement.parentElement.parentElement.parentElement;
  let noStocks = btnClicked.getElementsByClassName("out-of-stock-cover")[0];
  if (noStocks.style.display == "flex") return;
  let name = btnClicked.getElementsByClassName("product-name")[0].innerText;
  let price = parseFloat(
  btnClicked.
  getElementsByClassName("product-price")[0].
  innerText.replace("₹ ", ""));

  let imgSrc = btnClicked.getElementsByClassName("product-img")[0].src;
  SwitchBtns(btnClicked);
  let cartItem = {
    name,
    price,
    imgSrc,
    qty: 1 };

  CartItems(cartItem);
  cartDetails.push(cartItem);
  RenderCart();
  CartItemsTotal();
}

the remove item function when you click on trash icon in the cart then product find in cart details array and remove from it.

function removeItem(event) {
  let btnClicked = event.parentElement;
  let itemName = btnClicked.getElementsByClassName("name")[0].innerText;
  let productNames = document.getElementsByClassName("product-name");
  cartDetails.forEach((item, i) => {
    if (itemName == item.name) {
      cartDetails.splice(i, 1);
      for (let name of productNames) {
        if (itemName == name.innerText) {
          let found = name.parentElement.parentElement;
          SwitchBtns(found);
        }
      }
    }
  });
  RenderCart();
  CartIsEmpty();
  CartItemsTotal();
}

the clear cart function clear the cart items means come back to initial state.

function clearCart() {
  ToggleBackBtns();
  cartDetails.length = 0;
  RenderCart();
  CartIsEmpty();
  CartItemsTotal();
}

the quantity change function takes two parameters first is a current element and the second is the action of function addition or subtraction after that get the current product name and the product find in the cart details array. if the product exists in the list and action is added then increment +1 in the product and if action is sub then decrement -1 and you can only buy 10 items of each product.

function qtyChange(event, handler) {
  let btnClicked = event.parentElement.parentElement;
  let isPresent = btnClicked.classList.contains("btn-add");
  let itemName = isPresent ?
  btnClicked.parentElement.parentElement.getElementsByClassName(
  "product-name")[
  0].innerText :
  btnClicked.parentElement.getElementsByClassName("name")[0].innerText;
  let productNames = document.getElementsByClassName("product-name");
  for (let name of productNames) {
    if (itemName == name.innerText) {
      let productBtn = name.parentElement.parentElement.getElementsByClassName(
      "qty-change")[
      0];
      cartDetails.forEach((item, i) => {
        if (itemName == item.name) {
          if (handler == "add" && item.qty < 10) {
            item.qty += 1;
            btnClicked.innerHTML = QtyBtn(item.qty);
            productBtn.innerHTML = QtyBtn(item.qty);
          } else if (handler == "sub") {
            item.qty -= 1;
            btnClicked.innerHTML = QtyBtn(item.qty);
            productBtn.innerHTML = QtyBtn(item.qty);
            if (item.qty < 1) {
              cartDetails.splice(i, 1);
              productBtn.innerHTML = AddBtn();
              productBtn.classList.toggle("qty-change");
            }
          } else {
            document.getElementsByClassName("purchase-cover")[0].style.display =
            "block";
            document.getElementsByClassName("stock-limit")[0].style.display =
            "flex";
            sideNav(0);
          }
        }
      });
    }
  }
  RenderCart();
  CartIsEmpty();
  CartItemsTotal();
}
order now shopping cart javascript

So the limit purchase function checks the limit of each product which means you can only buy 10 items of each product. The side nav used for sidebar and buy, order, and okay functions when you come to the last step of the order like order has been completed, thanks for shopping, etc.

function limitPurchase(event) {
  document.getElementsByClassName("purchase-cover")[0].style.display = "none";
  event.parentElement.style.display = "none";
  sideNav(1);
}

function sideNav(handler) {
  let sideNav = document.getElementsByClassName("side-nav")[0];
  let cover = document.getElementsByClassName("cover")[0];
  sideNav.style.right = handler ? "0" : "-100%";
  cover.style.display = handler ? "block" : "none";
  CartIsEmpty();
}

function buy(handler) {
  if (cartDetails.length == 0) return;
  sideNav(!handler);
  document.getElementsByClassName("purchase-cover")[0].style.display = handler ?
  "block" :
  "none";
  document.getElementsByClassName("order-now")[0].innerHTML = handler ?
  Purchase() :
  "";
}

function order() {
  let invoice = document.getElementsByClassName("invoice")[0];
  invoice.style.height = "500px";
  invoice.style.width = "400px";
  invoice.innerHTML = OrderConfirm();
  ToggleBackBtns();
  Stocks();
  clearCart();
}

function okay(event) {
  let container = document.getElementsByClassName("invoice")[0];
  if (event.target.innerText == "continue") {
    container.style.display = "none";
    document.getElementsByClassName("purchase-cover")[0].style.display = "none";
  } else {
    event.target.innerText = "continue";
    event.target.parentElement.getElementsByClassName(
    "order-details")[
    0].innerHTML = `<em class='thanks'>Thanks for shopping with us</em>`;
    container.style.height = "180px";
  }
}

the quantity button function checking if quantity is 0 then calls an add btn function to return an add button but if quantity is 1 return an increment or decrements arrow HTML.

shopping cart sidebar add to cart

the cart item func returns the HTML of sidebar cart products and the last functions return the main page or sidebar HTML when you viewing the code then you will easily understand the code.

// button components for better Ux {
function AddBtn() {
  return `
<div>
  <button onclick='addItem(this)' class='add-btn'>Add <i class='fas fa-chevron-right'></i></button>
</div>`;
}

function QtyBtn(qty = 1) {
  if (qty == 0) return AddBtn();
  return `
<div>
  <button class='btn-qty' onclick="qtyChange(this,'sub')"><i class='fas fa-chevron-left'></i></button>
  <p class='qty'>${qty}</p>
  <button class='btn-qty' onclick="qtyChange(this,'add')"><i class='fas fa-chevron-right'></i></button>
</div>`;
}
//}

//Ui components {
function Product(product = {}) {
  let { name, price, imageUrl, heading, des } = product;
  return `
<div class='card'>
  <div class='top-bar'>
    <i class='fab fa-apple'></i>
    <em class="stocks">In Stock</em>
  </div>
  <div class='img-container'>
    <img class='product-img' src='${imageUrl}' alt='' />
    <div class='out-of-stock-cover'><span>Out Of Stock</span></div>
  </div>
  <div class='details'>
    <div class='name-fav'>
      <strong class='product-name'>${name}</strong>
      <button onclick='this.classList.toggle("fav")' class='heart'><i class='fas fa-heart'></i></button>
    </div>
    <div class='wrapper'>
      <h5>${heading}</h5>
      <p>${des}</p>
    </div>
    <div class='purchase'>
      <p class='product-price'>₹ ${price}</p>
      <span class='btn-add'>${AddBtn()}</span>
    </div>
  </div>
</div>`;
}

function CartItems(cartItem = {}) {
  let { name, price, imgSrc, qty } = cartItem;
  return `
<div class='cart-item'>
  <div class='cart-img'>
    <img src='${imgSrc}' alt='' />
  </div>
  <strong class='name'>${name}</strong>
  <span class='qty-change'>${QtyBtn(qty)}</span>
  <p class='price'>₹ ${price * qty}</p>
  <button onclick='removeItem(this)'><i class='fas fa-trash'></i></button>
</div>`;
}

function Banner() {
  return `
<div class='banner'>
  <ul class="box-area">
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  </ul>
  <div class='main-cart'>${DisplayProducts()}</div>

  <div class='nav'>
    <button onclick='sideNav(1)'><i class='fas fa-shopping-cart' style='font-size:2rem;'></i></button>
    <span class= 'total-qty'>0</span>
  </div>
  <div onclick='sideNav(0)' class='cover'></div>
  <div class='cover purchase-cover'></div>
  <div class='cart'>${CartSideNav()}</div>
  <div class='stock-limit'>
    <em>You Can Only Buy 10 Items For Each Product</em>
    <button class='btn-ok' onclick='limitPurchase(this)'>Okay</button>
  </div>
<div  class='order-now'></div>
</div>`;
}

function CartSideNav() {
  return `
<div class='side-nav'>
  <button onclick='sideNav(0)'><i class='fas fa-times'></i></button>
  <h2>Cart</h2>
  <div class='cart-items'></div>
  <div class='final'>
    <strong>Total: ₹ <span class='total'>0</span>.00/-</strong>
    <div class='action'>
      <button onclick='buy(1)' class='btn buy'>Purchase <i class='fas fa-credit-card' style='color:#6665dd;'></i></button>
      <button onclick='clearCart()' class='btn clear'>Clear Cart <i class='fas fa-trash' style='color:#bb342f;'></i></button>
    </div>
  </div>
</div>`;
}

when you add some products in the cart and click on purchase then purchase function first the func iterate the customer cart details and return item quantity with the name and item quantity multiple with each product price and calculate the total price of all cart products.

function Purchase() {
  let toPay = document.getElementsByClassName("total")[0].innerText;
  let itemNames = cartDetails.map(item => {
    return `<span>${item.qty} x ${item.name}</span>`;
  });
  let itemPrices = cartDetails.map(item => {
    return `<span>₹ ${item.price * item.qty}</span>`;
  });
  return `
<div class='invoice'>
  <div class='shipping-items'>
    <div class='item-names'>${itemNames.join("")}</div>
    <div class='items-price'>${itemPrices.join("+")}</div>
  </div>
<hr>
  <div class='payment'>
    <em>payment</em>
    <div>
      <p>total amount to be paid:</p><span class='pay'>₹ ${toPay}</span>
    </div>
  </div>
  <div class='order'>
    <button onclick='order()' class='btn-order btn'>Order Now</button>
    <button onclick='buy(0)' class='btn-cancel btn'>Cancel</button>
  </div>
</div>`;
}
complete order of add to cart or shopping cart
order has been placed popup

Now you see the order now button when you click on this then order confirm function calls they get the total price of the products and return it in the same popup inside have order id or total cost of the products that you have paid and after that have some small function that has been used during the process.

function OrderConfirm() {
  let orderId = Math.round(Math.random() * 1000);
  let totalCost = document.getElementsByClassName("total")[0].innerText;
  return `
<div>
  <div class='order-details'>
    <em>your order has been placed</em>
    <p>Your order-id is : <span>${orderId}</span></p>
    <p>your order will be delivered to you in 3-5 working days</p>
    <p>you can pay <span>₹ ${totalCost}</span> by card or any online transaction method after the products have been dilivered to you</p>
  </div>
  <button onclick='okay(event)' class='btn-ok'>okay</button>
</div>`;
}

unction DisplayProducts() {
  let products = productDetails.map(product => {
    return Product(product);
  });
  return products.join("");
}

function DisplayCartItems() {
  let cartItems = cartDetails.map(cartItem => {
    return CartItems(cartItem);
  });
  return cartItems.join("");
}

function RenderCart() {
  document.getElementsByClassName(
  "cart-items")[
  0].innerHTML = DisplayCartItems();
}

function SwitchBtns(found) {
  let element = found.getElementsByClassName("btn-add")[0];
  element.classList.toggle("qty-change");
  let hasClass = element.classList.contains("qty-change");
  found.getElementsByClassName("btn-add")[0].innerHTML = hasClass ?
  QtyBtn() :
  AddBtn();
}

function ToggleBackBtns() {
  let btns = document.getElementsByClassName("btn-add");
  for (let btn of btns) {
    if (btn.classList.contains("qty-change")) {
      btn.classList.toggle("qty-change");
    }
    btn.innerHTML = AddBtn();
  }
}

function CartIsEmpty() {
  let emptyCart = `<span class='empty-cart'>Looks Like You Haven't Added Any Product In The Cart</span>`;
  if (cartDetails.length == 0) {
    document.getElementsByClassName("cart-items")[0].innerHTML = emptyCart;
  }
}
thanks for shopping
thanks for shopping popup

the cart item total function used for when you add products in the cart then they return an all necessary calculation that we need in the cart like total price of the cart item, quantity multiple by product price and return it. the last functions used for checking products under Stocks or OutOfStock.

function CartItemsTotal() {
  let totalPrice = cartDetails.reduce((totalCost, item) => {
    return totalCost + item.price * item.qty;
  }, 0);
  let totalQty = cartDetails.reduce((total, item) => {
    return total + item.qty;
  }, 0);
  document.getElementsByClassName("total")[0].innerText = totalPrice;
  document.getElementsByClassName("total-qty")[0].innerText = totalQty;
}

function Stocks() {
  cartDetails.forEach(item => {
    productDetails.forEach(product => {
      if (item.name == product.name && product.qty >= 0) {
        product.qty -= item.qty;
        if (product.qty < 0) {
          product.qty += item.qty;
          document.getElementsByClassName("invoice")[0].style.height = "180px";
          document.getElementsByClassName(
          "order-details")[
          0].innerHTML = `<em class='thanks'>Stocks Limit Exceeded</em>`;
        } else if (product.qty == 0) {
          OutOfStock(product, 1);
        } else if (product.qty <= 5) {
          OutOfStock(product, 0);
        }
      }
    });
  });
}

function OutOfStock(product, handler) {
  let products = document.getElementsByClassName("card");
  for (let items of products) {
    let stocks = items.getElementsByClassName("stocks")[0];
    let name = items.getElementsByClassName("product-name")[0].innerText;
    if (product.name == name) {
      if (handler) {
        items.getElementsByClassName("out-of-stock-cover")[0].style.display =
        "flex";
        stocks.style.display = "none";
      } else {
        stocks.innerText = "Only Few Left";
        stocks.style.color = "orange";
      }
    }
  }
}

the app function initalize the shopping cart javascript complete tutorial in the template.

function App() {
  return `
<div>
  ${Banner()}
</div>`;
}
//}

// injects the rendered component's html
document.getElementById("app").innerHTML = App();

if you liked the article and share it with your friends and if you have any questions about the article feel free to leave me a comment and I will answer the question you have and that’s about it hopefully I will see you again in another article.

4 thoughts on “Shopping Cart JavaScript complete tutorial

  • May 6, 2021 at 10:49 pm
    Permalink

    please, give me code html

    Reply
    • May 7, 2021 at 5:32 am
      Permalink

      In the html file have a one main div app all of the content comes from the js file please check

      Reply
  • May 13, 2021 at 3:08 am
    Permalink

    https://secrety.info – все скидки на доставку на одном сайте!
    Что это такое: промо код на скидку?
    Многие хотя бы раз заказывали через интернет. И видели такое поле при оформлении как “Введите код на скидку”. Ну а где же его брать, размышляли вы. Итак, промокод это последовательность букв и символов, с помощью которой можно получить право на скидку. Мы создали наш сайт для того, чтобы решить этот вопрос раз и навсегда.
    Здесь вы найдете десятки тысяч бесплатных купонов во все интернет-магазины и сервисы. Копируйте промокод и пишите его в специальном место в интернет-магазине при оформлении заказа и вы получите приятную скидку. Ага, все вот так просто!

    Reply

Leave a Reply

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