DEV Community

Cover image for How to add items to your cart with Tailwind CSS and JavaScript
Michael Andreuzza
Michael Andreuzza

Posted on

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

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

See it live and get the code

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.
html
<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.
  • ${item.name} x${item.quantity} - $${item.price * item.quantity}: This sets the inner HTML of the list item to display the name, quantity, and price of the item.
  • +: This creates a button that increases the quantity of the item when clicked.
  • -: This creates a button that decreases the quantity of the item when clicked.
  • Remove: 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.

vDecrease 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.

Image description

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!

Top comments (2)

Collapse
 
dung_nguyen_3d9ec24ffda4d profile image
Dzung Nguyen πŸ‡»πŸ‡³

A bit difficult to read but totally quite easy to understand. Thank for your sharing. 🀘🀘🀘🀘🀘

Collapse
 
mike_andreuzza profile image
Michael Andreuzza • Edited

I know man, i have issues with liquid tags for two days when copy pasting the markdown from my site, and don't know why is giving me issues....

So i had to remove the backticks