JavaScript Shopping Cart with Total Price

JavaScript Shopping Cart with Total Price
Code Snippet:Shopping Cart with Total Price
Author: Susan Lee
Published: January 11, 2024
Last Updated: January 22, 2024
Downloads: 27,899
License: MIT
Edit Code online: View on CodePen
Read More

This lightweight JavaScript code snippet helps you to create a minimal shopping cart template with a total price counter. It comes with a nice UI design that includes a products list with thumbnails and add to cart button. Users can easily add products to the cart list and the JS function automatically count the total price.

Basically, this code snippet only provides a general concept to count the values of items on the front end. You can integrate this code into your shopping project to calculate the product’s prices. It can be highly customized with additional CSS.

How to Create JavaScript Shopping Cart with Total Price

1.  First of all, create an unordered list of items with the class name "menu-item" and place the item’s name and price. Similarly, create add to cart button and place the data-price attribute to each button that will be used in the JavaScript program to count the total price. So, a basic HTML structure for the shopping cart is as follows:

 <div class="container">
  <div class="screen-togo">
    <h2>To Go Menu</h2>
    <ul class="menu-items">
      <!--    Menu Item 1    -->
      <li class="menu-item">
        <img src="./img/plate__french-fries.webp" alt="French Fries with Ketchup" class="menu-image">
        <div class="menu-item-dets">
          <p class="menu-item-heading">French Fries with Ketchup</p>
          <p class="g-price">$2.23</p>
        </div>
        <button
          class="add-button"
          data-title="French Fies with Ketchup"
          data-price="2.23">Add to Cart</button>
      </li>
      <!--    Menu Item 2    -->
      <li class="menu-item">
        <img src="./img/plate__salmon-vegetables.webp" alt="Salmon and Vegetables" class="menu-image">
        <div class="menu-item-dets">
          <p class="menu-item-heading">Salmon and Vegetables</p>
          <p class="g-price">$8.99</p>
        </div>
        <button
          class="add-button"
          data-title="Salmon and Vegetables"
          data-price="8.99">Add to Cart</button>
      </li>
      <!--    Menu Item 3    -->
      <li class="menu-item">
        <img src="./img/plate__spaghetti-meat-sauce.webp" alt="Spaghetti with Sauce" class="menu-image">
        <div class="menu-item-dets">
          <p class="menu-item-heading">Spaghetti with Sauce</p>
          <p class="g-price">$7.89</p>
        </div>
        <button
          class="add-button"
          data-title="Spaghetti with Sauce"
          data-price="7.89">Add to Cart</button>
      </li>
      <!--    Menu Item 4    -->
      <li class="menu-item">
        <img src="./img/plate__tortellini.webp" alt="Tortellini" class="menu-image">
        <div class="menu-item-dets">
          <p class="menu-item-heading">Tortellini</p>
          <p class="g-price">$8.99</p>
        </div>
        <button 
          class="add-button"
          data-title="Tortellini"
          data-price="8.99"
          >Add to Cart</button>
      </li>
      <!--    Menu Item 5    -->
      <li class="menu-item">
        <img src="./img/plate__chicken-salad.webp" alt="Chicken Salad" class="menu-image">
        <div class="menu-item-dets">
          <p class="menu-item-heading">Chicken Salad</p>
          <p class="g-price">$5.75</p>
        </div>
        <button
          class="add-button"
          data-title="Chicken Salad"
          data-price="5.75">Add to Cart</button>
      </li>
    </ul>
  </div>
  <div class="screen-cart">
    <h2>Your Cart</h2>
    <!--  Cart Items -->
    <ul class="cart-items">
    </ul>
    
    <div class="cart-math">
      <p>Add items to cart</p>
    </div>
  </div>
</div>  

2. After that, you need to set the basic style for the shopping cart interface. You can style the shopping page according to your needs. Anyhow, the following are the basic styles for the products list. You can modify these styles to get the desired output.

body {
  background-image: url('../img/background.webp');
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  min-height: 100vh;
  font-family: "Poppins", sans-serif;
}

h2, .g-price {
  font-size: 32px;
  font-weight: 700;
  margin-bottom: 50px;
}

.g-price {
  margin: 8px 0;
}

.container {
  width: 90%;
  max-width: 780px;
  margin: 0 auto;
  padding: 70px 0;
  display: flex;
  justify-content: space-between;
}

@media (max-width: 950px) {
  .container {
    display: block;
  }
}
.screen-togo, .screen-cart {
  width: 375px;
  max-height: 770px;
  overflow: scroll;
  border-radius: 25px;
  background: white;
  padding-top: 30px;
  padding-left: 30px;
  margin: 20px;
  box-shadow: 0px 0px 70px rgba(0, 0, 0, 0.1);
}

ul {
  padding: 0;
  list-style: none;
}

.menu-item {
  background: #E4F0FD;
  border-radius: 20px 0 0 20px;
  margin: 30px 0;
  padding-top: 15px;
  padding-right: 30px;
  padding-bottom: 10px;
  position: relative;
}
.menu-item:nth-child(2n) {
  background: #FBE4F0;
}
.menu-item:nth-child(3n) {
  background: #F7F7FE;
}
.menu-item:nth-child(4n) {
  background: #E4FDF1;
}
.menu-item img {
  width: 150px;
  position: absolute;
  top: -20px;
  left: -20px;
}
.menu-item .add-button {
  position: absolute;
  border: none;
  background: #6B00F5;
  padding: 6px 20px 4px;
  border-radius: 20px;
  color: white;
  font-weight: 700;
  font-size: 16px;
  bottom: -10px;
  left: 150px;
  transition: all 0.3s;
}
.menu-item .add-button:hover {
  background: #5815AE;
}

.menu-item-dets {
  margin-left: 150px;
  padding-bottom: 15px;
}

.menu-item-heading {
  font-size: 18px;
  margin: 10px 0 12px;
}

.screen-cart {
  padding-right: 30px;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translate(10px);
  }
  to {
    opacity: 1;
    transform: translate(0);
  }
}
.cart-item {
  display: flex;
  align-items: flex-start;
  padding-bottom: 25px;
  margin-bottom: 25px;
  border-bottom: 1px solid #D7D7F9;
  animation: fadeIn 0.3s;
}
.cart-item:last-child {
  border-bottom: 5px solid #D7D7F9;
}
.cart-item img {
  width: 65px;
}
.cart-item .g-price {
  font-size: 24px;
}

.cart-item-dets {
  margin-left: 15px;
  width: 100%;
}

.cart-item-heading {
  margin: 10px 0;
}

.cart-math-item {
  margin: 5px 0;
  font-weight: 700;
}
.cart-math-item span {
  display: inline-block;
  text-align: right;
}
.cart-math-item .cart-math-header {
  width: 50%;
}
.cart-math-item .g-price {
  width: 40%;
}

3. After creating the basic structure for the shopping cart, now it’s time to functionalize the add to cart and total price. So, load the jQuery by adding the following CDN link to your HTML page.

<!-- jQuery -->
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js'></script>

4. Finally, add the following JavaScript code just after the jQuery script and done.

let subtotal = 0;

const calculateTax = subtotal => {
  const tax = subtotal * 0.13;
  const formattedTax = tax.toFixed(2);
  return formattedTax;
};

const calculateTotal = subtotal => {
  const tax = calculateTax(subtotal);
  const total = parseFloat(subtotal) + parseFloat(tax);
  const formattedTotal = total.toFixed(2);
  return formattedTotal;
};

const getImgLink = title => {
  let imgLink;
  switch (title) {
    case 'French Fies with Ketchup':
      imgLink = 'https://assets.codepen.io/687837/plate__french-fries.png';
      break;
    case 'Salmon and Vegetables':
      imgLink = 'https://assets.codepen.io/687837/plate__salmon-vegetables.png';
      break;
    case 'Spaghetti with Sauce':
      imgLink = 'https://assets.codepen.io/687837/plate__spaghetti-meat-sauce.png';
      break;
    case 'Tortellini':
      imgLink = 'https://assets.codepen.io/687837/plate__tortellini.png';
      break;
    case 'Chicken Salad':
      imgLink = 'https://assets.codepen.io/687837/plate__chicken-salad.png';
      break;
    default:
      imgLink = 'https://assets.codepen.io/687837/plate__chicken-salad.png';}

  return imgLink;
};

$('.add-button').on('click', function () {
  const title = $(this).data('title');
  const price = $(this).data('price');
  const imgLink = getImgLink(title);

  const element = `
    <li class="cart-item">
      <img src="${imgLink}" alt="${title}">
      <div class="cart-item-dets">
        <p class="cart-item-heading">${title}</p>
        <p class="g-price">$${price}</p>
      </div>
    </li>
  `;
  $('.cart-items').append(element);

  subtotal = subtotal + price;

  const formattedSubtotal = subtotal.toFixed(2);
  const tax = calculateTax(subtotal);
  const total = calculateTotal(subtotal);

  $('.cart-math').html(`
    <p class="cart-math-item">
      <span class="cart-math-header">Subtotal:</span>
      <span class="g-price subtotal">$${formattedSubtotal}</span>
    </p>
    <p class="cart-math-item">
      <span class="cart-math-header">Tax:</span>
      <span class="g-price tax">$${tax}</span>
    </p>
    <p class="cart-math-item">
      <span class="cart-math-header">Total:</span>
      <span class="g-price total">$${total}</span>
    </p>
  `);
});

That’s all! I hope you have successfully integrated this shopping cart minimal template into your project. If you have any questions or suggestions, let me know by comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X