← Back to all tutorials

How to add items to your cart with Tailwind CSS and JavaScript

Cart page with items added to the cart
Published and written on Jun 05 2024 by Michael Andreuzza

Let’s recreate the same cart example using JavaScript instead of Alpine.js.

A quick refresh: What are add to cart buttons and what do they do?

Add to cart buttons are used to add items to the cart. They typically have a “Add to Cart” text or icon next to them. When clicked, the button will add the item to the cart and display the total price of the cart or how many items are in the cart.

Use Cases:

  • Shopping carts: A shopping cart is a list of items that a customer can add to their cart and then checkout.
  • Product listings: A product listing is a list of products that a customer can add to their cart and then checkout.
  • Online stores: An online store is a website that sells products and allows customers to add them to their cart and then checkout.
  • E-commerce websites: An e-commerce website is a website that sells products and allows customers to add them to their cart and then checkout.

This is the structure of the project: Understanding the code:

  • ìd=“app”`: This is the data object that holds the cart items and their quantities.
  • id="prduct-list": This is the list of products.
  • data-id="1": This is the id of the first product.
  • <button class="add-to-cart ..."> Add to Cart </button>: This is a button that adds a product to the cart when clicked.
  • id="cart-list": This is the list of items in the cart.
  • id="total-price": This is the total price of the cart items.

Classes are removed for brevity, but I’ll keep those classes relevant to the tutorial.

 <div id="app">
   <!-- Product List -->
   <ul id="product-list">
     <li data-id="1">
       <div>
         <span>Tomatoes</span> - <span>$10</span>
       </div>
       <button class="add-to-cart ..."> Add to Cart </button>
     </li>
     <!-- Add more products here -->
   </ul>
   <!-- Cart -->
   <div>
     <h4>Your items</h4>
     <ul id="cart-list">
       <!-- Cart items will be hardcoded here -->
     </ul>
     <div>Total Price: $ <span id="total-price">0</span>
     </div>
   </div>
 </div>

The Script

  • document.addEventListener("DOMContentLoaded", function() {: This is the event listener that runs when the DOM is fully loaded.

Product List

  • const products = [{: This is an array of objects that represent the products in the cart.
  • id: 1,: This is the id of the first product.
  • name: "Tomatoes",: This is the name of the first product.
  • price: 10: This is the price of the first product.

Cart

  • const cart = [];: This is an empty array that will hold the cart items.

Render Cart

  • function renderCart() {: This is a function that will render the cart.
  • const cartList = document.getElementById("cart-list");: This is the list of items in the cart.
  • cartList.innerHTML = "";: This clears the list of items in the cart.
  • cart.forEach((item, index) => {: This loops through each item in the cart and renders it in the list.
  • const li = document.createElement("li");: This creates a new list item.
  • li.innerHTML = : This sets the inner HTML of the list item.
  • <span>${item.name} x${item.quantity}</span> - $<span>${item.price * item.quantity}</span>: This sets the inner HTML of the list item to display the name, quantity, and price of the item.
  • <button class="increase-quantity ...">+</button>: This creates a button that increases the quantity of the item when clicked.
  • <button class="decrease-quantity ...">-</button>: This creates a button that decreases the quantity of the item when clicked.
  • <button class="remove-from-cart ...">Remove</button>: This creates a button that removes the item from the cart when clicked.
  • li.querySelector(".increase-quantity").addEventListener("click", () => {: This adds an event listener to the increase quantity button.
  • increaseQuantity(index): This is the function that will increase the quantity of the item when clicked.
  • li.querySelector(".decrease-quantity").addEventListener("click", () => {: This adds an event listener to the decrease quantity button.
  • decreaseQuantity(index): This is the function that will decrease the quantity of the item when clicked.
  • li.querySelector(".remove-from-cart").addEventListener("click", () => {: This adds an event listener to the remove from cart
  • removeFromCart(index): This is the function that will remove the item from the cart when clicked.

Add to Cart

  • function addToCart(product) {: This is a function that adds a product to the cart.
  • const existingItem = cart.find((item) => item.id === product.id);: This finds the existing item in the cart with the same id as the product.
  • if (existingItem) {: This checks if the existing item is found.
  • existingItem.quantity++;: This increases the quantity of the existing item.
  • } else {: This creates a new item in the cart.
  • cart.push({: This pushes the new item to the cart.
  • ...product,: This spreads the product object into the new item.
  • quantity: 1: This sets the quantity of the new item to 1.
  • renderCart();: This calls the renderCart function to update the cart.

Remove from Cart

  • function removeFromCart(index) {: This is a function that removes an item from the cart.
  • cart.splice(index, 1);: This removes the item at the specified index from the cart.
  • renderCart();: This calls the renderCart function to update the cart.

Increase Quantity

  • function increaseQuantity(index) {: This is a function that increases the quantity of an item in the cart.
  • cart[index].quantity++;: This increases the quantity of the item at the specified index in the cart.
  • renderCart();: This calls the renderCart function to update the cart.

Decrease Quantity

  • function decreaseQuantity(index) {: This is a function that decreases the quantity of an item in the cart.
  • if (cart[index].quantity > 1) {: This checks if the quantity of the item at the specified index is greater than 1.
  • cart[index].quantity--;: This decreases the quantity of the item at the specified index in the cart.
  • } else {: This checks if the quantity of the item at the specified index is less than or equal to 1.
  • removeFromCart(index);: This removes the item at the specified index from the cart.

Total Price

  • function totalPrice() {: This is a function that calculates the total price of the cart items.
  • return cart.reduce((total, item) => total + item.price * item.quantity, 0);: This reduces the cart items to a single value by multiplying the price and quantity of each item and adding them together.
  • document.getElementById("total-price").textContent = totalPrice();: This sets the text content of the total price element to the calculated total price.
  • button.addEventListener("click", (event) => {: This adds an event listener to the total price button.
  • const productId = parseInt(event.target.closest("li").dataset.id);: This gets the id of the product that was clicked.
  • const product = products.find((p) => p.id === productId);: This finds the product with the specified id.
  • addToCart(product);: This adds the product to the cart.
 document.addEventListener("DOMContentLoaded", function() {
     const products = [{
             id: 1,
             name: "Tomatoes",
             price: 10
         },
         // Add more products here
     ];

     const cart = [];

     function renderCart() {
         const cartList = document.getElementById("cart-list");
         cartList.innerHTML = "";

         cart.forEach((item, index) => {
             const li = document.createElement("li");
             li.innerHTML = `
            <span>${item.name} x${item.quantity}</span> - $<span>${item.price * item.quantity}</span>
            <button class="increase-quantity ...">+</button>
            <button class="decrease-quantity ...">-</button>
            <button class="remove-from-cart ...">Remove</button>
          `;

             li.querySelector(".increase-quantity").addEventListener("click", () =>
                 increaseQuantity(index)
             );
             li.querySelector(".decrease-quantity").addEventListener("click", () =>
                 decreaseQuantity(index)
             );
             li.querySelector(".remove-from-cart").addEventListener("click", () =>
                 removeFromCart(index)
             );

             cartList.appendChild(li);
         });

         document.getElementById("total-price").textContent = totalPrice();
     }

     function addToCart(product) {
         const existingItem = cart.find((item) => item.id === product.id);
         if (existingItem) {
             existingItem.quantity++;
         } else {
             cart.push({
                 ...product,
                 quantity: 1
             });
         }
         renderCart();
     }

     function removeFromCart(index) {
         cart.splice(index, 1);
         renderCart();
     }

     function increaseQuantity(index) {
         cart[index].quantity++;
         renderCart();
     }

     function decreaseQuantity(index) {
         if (cart[index].quantity > 1) {
             cart[index].quantity--;
         } else {
             removeFromCart(index);
         }
         renderCart();
     }

     function totalPrice() {
         return cart.reduce(
             (total, item) => total + item.price * item.quantity,
             0
         );
     }

     document.querySelectorAll(".add-to-cart").forEach((button) => {
         button.addEventListener("click", (event) => {
             const productId = parseInt(event.target.closest("li").dataset.id);
             const product = products.find((p) => p.id === productId);
             addToCart(product);
         });
     });

     renderCart();
 });

Conclusion

In this tutorial, we learned how to add items to a cart using JavaScript and Tailwind CSS. We created a simple cart that allows users to add items to the cart and display the total price of the cart.

Hope you enjoyed this tutorial and had fun!

/Michael Andreuzza

Did you like this tutorial? Please share it with your friends!

Get lifetime access to every theme available today for $199 $139 and own them forever. Plus, new themes, lifetime updates, use on unlimited projects and enjoy lifetime support.

— No subscription required!