JavaScript Add to Cart with Local Storage

JavaScript Add to Cart with Local Storage
Code Snippet:[JS] Using Local Storage as (kind of) Redux (WIP)
Author: Henry Zeitler
Published: January 9, 2024
Last Updated: January 22, 2024
Downloads: 857
License: MIT
Edit Code online: View on CodePen
Read More

This code snippet provides functionality to manage a shopping cart using JavaScript and local storage. It allows you to add items to a cart, display the cart’s contents, and empty the cart.

This code works by utilizing JavaScript functions for adding, retrieving, and deleting cart items in local storage. It helps you create a simple shopping cart for your website, making it easy to manage items added by users.

You can use this code in your e-commerce web projects to implement a user-friendly shopping cart feature. It helps improve the user experience by allowing customers to add and view items in their cart.

How to Create Add To Cart Using JavaScript and Local Storage

1. First of all, load the Normalize CSS by adding the following CDN link into the head tag of your HTML document.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">

2. Create the HTML structure for the shopping cart as follows. It contains sections for the header, main content, and buttons for adding items to the cart. Ensure the necessary classes are in place for styling and functionality.

<header class="header">
  <div class="header__wrapper">
    <h1 class="header__headline">LocalStorageCart</h1>

    <section class="cart">
      <h2 class="cart__headline">My cart</h2>
      <button id="js-delete-cart">Empty cart</button>
      <ul class="cart__shoppingList" id="js-item-list"></ul>
    </section>
  </div>
</header>

<main class="main">
  <ul class="main__wrapper">
    
    <li class="teaser">
      <div class="teaser__wrapper">
        <h3 class="teaser__headline">Item 01</h3>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nulla numquam quidem voluptate deleniti sunt! Quaerat.</p>
        <p><button class="teaser__cta js-buy-button" data-title="Item 01" data-price="20,00 €">Add to cart</button>
      </div>
    </li>
    
    <li class="teaser">
      <div class="teaser__wrapper">
        <h3 class="teaser__headline">Item 02</h3>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nulla numquam quidem voluptate deleniti sunt! Quaerat.</p>
        <p><button class="teaser__cta js-buy-button" data-title="Item 02" data-price="12,50 €">Add to cart</button>
      </div>
    </li>
    
    <li class="teaser">
      <div class="teaser__wrapper">
        <h3 class="teaser__headline">Item 03</h3>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nulla numquam quidem voluptate deleniti sunt! Quaerat.</p>
        <p><button class="teaser__cta js-buy-button" data-title="Item 03" data-price="37,90 €">Add to cart</button>
      </div>
    </li>
    
  </ul>
</main>

3. Now, add the following CSS code to your project to style the basic interface of the shopping cart. You can modify the CSS rules according to your needs.

.header {
  background: #26282c;
  color: #fff;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
}
.header__wrapper {
  padding: 20px;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-between;
  align-content: stretch;
  align-items: flex-start;
  max-width: 1280px;
  margin: 0 auto;
}
.header__headline {
  margin: 0;
}

.cart {
  width: 200px;
  position: relative;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-between;
  align-content: stretch;
  align-items: center;
}
.cart__headline {
  margin: 0;
}
.cart__shoppingList {
  list-style: none;
  padding: 0;
  position: absolute;
  right: -20px;
  top: 40px;
  width: 400px;
  background: #26282c;
}
.cart__shoppingList__item {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-between;
  align-content: stretch;
  align-items: flex-start;
  padding: 10px 20px;
}
.cart__shoppingList__item h3, .cart__shoppingList__item p {
  margin: 0;
}

.main {
  margin-top: 100px;
  background: #26282c;
}
.main__wrapper {
  padding: 20px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
  align-content: stretch;
  align-items: flex-start;
  max-width: 1280px;
  margin: 0 auto;
}

.teaser {
  list-style: none;
  padding: 0;
  margin: 0 0 4% 0;
  border: 1px solid #eee;
  box-sizing: border-box;
  order: 0;
  flex: 0 0 48%;
  width: 48%;
  align-self: auto;
  background: #ebebeb;
}
.teaser__wrapper {
  padding: 20px;
}

body {
  background: #26282c;
}

4. The JavaScript functions to manage the cart’s functionality. These functions handle adding items to the cart, retrieving cart data, deleting items, and displaying the updated cart content. Add the following code between <script> tag (or external JS file) just before closing the body tag.

function setCart(item, payload) {
  localStorage.setItem(item, payload);
}

function getCart(item) {
  let cartData = localStorage.getItem(item);
  return cartData;
}

function deleteCart(item) {
  localStorage.removeItem(item);
}

function addToCartHandler() {
  const storageCartName = 'cart';
  let addButton = document.querySelectorAll('.js-buy-button');

  addButton.forEach(elem => {
    elem.addEventListener('click', function () {
      let itemTitle = elem.dataset.title;
      let itemPrice = elem.dataset.price;
      let itemPayload = {
        'title': itemTitle,
        'price': itemPrice };

      let currentCart = JSON.parse(getCart(storageCartName));
      let changeCartEvent = new Event('itemInserted');

      if (currentCart === null) {
        currentCart = { 'items': [] };
      }
      currentCart.items.push(itemPayload);
      setCart(storageCartName, JSON.stringify(currentCart));
      document.dispatchEvent(changeCartEvent);
    });
  });
};

function listenToCartHandler() {
  let cartData = JSON.parse(getCart('cart'));
  let shoppingListContainer = document.querySelector('#js-item-list');
  shoppingListContainer.innerHTML = '';

  if (cartData !== null) {
    cartData.items.forEach(elem => {
      let shoppingListTemplate = `
        <li class="cart__shoppingList__item">
          <h3>${elem.title}</h3>
          <p>Price: ${elem.price}</p>
        </li>
        `;
      shoppingListContainer.innerHTML += shoppingListTemplate;
    });
  }
}

function emptyCart() {
  let deleteButton = document.querySelector('#js-delete-cart');
  deleteButton.addEventListener('click', function () {
    deleteCart('cart');
    listenToCartHandler();
  });
}

// Init
listenToCartHandler();
document.addEventListener("itemInserted", listenToCartHandler, false);
addToCartHandler();
emptyCart();

That’s all! hopefully, you have successfully created add-to-cart functionality using JavaScript and local storage. If you have any questions or suggestions, feel free to 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