Build a Functional Shopping Cart with JavaScript

Build a Functional Shopping Cart with JavaScript

Table of Contents:

  1. Introduction
  2. Setting Up the Project
  3. Adding Functionality to Remove Items from Cart
  4. Updating the Cart Total
  5. Adding Items to the Cart
  6. Removing Items from the Cart
  7. Updating Quantity and Total
  8. Making a Purchase
  9. Cleaning Up the Code
  10. Conclusion

Introduction

Welcome to this tutorial on how to code a shopping cart using vanilla JavaScript. In this video, we will create a fully functional shopping cart that allows users to add and remove items, update quantity, and make purchases. We will start by setting up the project and then proceed to add the necessary functionality step by step. By the end of this tutorial, you will have a fully working shopping cart that you can integrate into your website.

🛒 Set Up the Project To begin, we will set up the project by creating the necessary HTML structure and linking a JavaScript file. We will also add the CSS styles required for the shopping cart.

🗑️ Adding Functionality to Remove Items from Cart Next, we will add functionality to the remove buttons in the cart. When a user clicks on the remove button, it should remove the corresponding item from the cart and update the total price accordingly.

💰 Updating the Cart Total In this step, we will write code to update the total price of the cart whenever an item is added or removed. The total price should always reflect the current quantity and prices of the items in the cart.

🛍️ Adding Items to the Cart Now, we will implement the functionality to add items to the cart. When a user clicks on the "Add to Cart" button, the item should be added to the cart with the correct details, such as name, price, and quantity.

🗑️ Removing Items from the Cart In this step, we will handle the removal of items from the cart. When a user clicks on the remove button of an item in the cart, it should be removed from the cart, and the total price should be updated accordingly.

🔢 Updating Quantity and Total To provide a seamless user experience, we will allow users to update the quantity of items directly in the cart. When the quantity is updated, the total price should be recalculated and displayed accurately.

💸 Making a Purchase Once the user has added all the desired items to the cart, they can proceed to make a purchase. Clicking the purchase button will display a confirmation message and remove all the items from the cart.

✨ Cleaning Up the Code In this step, we will clean up our JavaScript code, ensuring it is well-structured and follows best practices. We will also remove any unnecessary code and comments.

🎉 Conclusion Congratulations! You have successfully created a fully functional shopping cart using vanilla JavaScript. You now have the knowledge and skills to integrate this shopping cart into your own website and enhance the user experience for your customers.

In the next sections, we will go through each of these steps in detail, providing code examples and explanations along the way.

Introduction

Welcome to this tutorial on how to code a shopping cart using vanilla JavaScript. In this tutorial, we will walk you through the steps of building a fully functional shopping cart that allows users to add and remove items, update quantity, and make purchases. By the end of this tutorial, you will have a robust shopping cart that you can integrate into your website.

Setting Up the Project

To get started, let's set up the project by creating the necessary HTML structure and linking a JavaScript file. We will also add CSS styles to make the shopping cart visually appealing.

First, create a new HTML file and name it "index.html". Inside the file, add the basic HTML structure and include the necessary CSS and JavaScript files. We recommend using external files for better code organization.

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Shopping Cart</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <h1>Shopping Cart</h1>

  <!-- Shopping Cart UI -->

  <script src="script.js"></script>
</body>
</html>

Next, create a CSS file named "styles.css" and link it in the HTML file. In the CSS file, you can add styles to format and position the different elements of the shopping cart.

/* Add your CSS styles here */

Now, create a JavaScript file named "script.js" and link it in the HTML file. This is where we will write the code to add the functionality to our shopping cart.

// Add your JavaScript code here

With the basic setup in place, we can move on to adding the functionality to our shopping cart.

Adding Functionality to Remove Items from Cart

In this step, we will add functionality to the remove buttons in the cart. When a user clicks on the remove button for an item, it should be removed from the cart, and the total price should be updated accordingly.

To accomplish this, we will need to select all the remove buttons and add an event listener to each button. Inside the event listener function, we will remove the corresponding item from the cart and update the total price. Let's go ahead and implement this functionality.

First, let's select all the remove buttons by their class name.

const removeButtons = document.getElementsByClassName('remove-button');

Next, let's loop over the remove buttons and add an event listener to each button.

for (let i = 0; i < removeButtons.length; i++) {
  const button = removeButtons[i];
  button.addEventListener('click', removeCartItem);
}

Now, let's define the removeCartItem function that will be called when the remove button is clicked.

function removeCartItem(event) {
  const buttonClicked = event.target;
  buttonClicked.parentElement.parentElement.remove();
  updateCartTotal();
}

In the removeCartItem function, we first get a reference to the remove button that was clicked using event.target. We then navigate to the parent elements to access the entire cart row and remove it from the DOM.

After removing the cart row, we call the updateCartTotal function to recalculate the total price.

Now, when a user clicks on the remove button for an item, it will be removed from the cart, and the total price will be updated accordingly.

Updating the Cart Total

In this step, we will write code to update the total price of the cart whenever an item is added or removed. The total price should always reflect the current quantity and prices of the items in the cart.

To accomplish this, we will need to iterate over each cart row, calculate the price for each item, and add them up to get the total price. Let's implement this functionality.

First, let's define the updateCartTotal function.

function updateCartTotal() {
  const cartRows = document.getElementsByClassName('cart-row');
  let total = 0;

  for (let i = 0; i < cartRows.length; i++) {
    const cartRow = cartRows[i];
    const priceElement = cartRow.getElementsByClassName('cart-price')[0];
    const quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0];

    const price = parseFloat(priceElement.innerText.replace('$', ''));
    const quantity = quantityElement.value;

    total += price * quantity;
  }

  // Round the total to two decimal places
  total = Math.round(total * 100) / 100;

  const totalElement = document.getElementsByClassName('cart-total-price')[0];
  totalElement.innerText = '$' + total;
}

In the updateCartTotal function, we first select all the cart rows by their class name. Then, we iterate over each cart row and retrieve the price and quantity elements. We extract the price value by parsing the inner text of the price element and removing the '$' symbol. We get the quantity value from the value property of the quantity element, which is an input element.

Using the retrieved price and quantity values, we calculate the subtotal for each cart row by multiplying the price and quantity. We increment the total by adding the subtotal to it.

After calculating the total, we round it to two decimal places using the Math.round function. Finally, we update the inner text of the total price element to display the new total.

Now, whenever an item is added or removed from the cart, the total price will be updated automatically.

Adding Items to the Cart

Now that we have implemented the functionality to remove items from the cart and update the total price, let's add the functionality to add items to the cart. When a user clicks on the "Add to Cart" button, the item should be added to the cart with the correct details, such as name, price, and quantity.

To accomplish this, we will need to select all the "Add to Cart" buttons and add an event listener to each button. Inside the event listener function, we will access the details of the item being added and create a new cart row with those details. Let's proceed with the implementation.

First, let's select all the "Add to Cart" buttons by their class name.

const addToCartButtons = document.getElementsByClassName('add-to-cart-button');

Next, let's loop over the "Add to Cart" buttons and add an event listener to each button.

for (let i = 0; i < addToCartButtons.length; i++) {
  const button = addToCartButtons[i];
  button.addEventListener('click', addToCartClicked);
}

Now, let's define the addToCartClicked function that will be called when an "Add to Cart" button is clicked.

function addToCartClicked(event) {
  const button = event.target;
  const shopItem = button.parentElement.parentElement;
  const title = shopItem.getElementsByClassName('shop-item-title')[0].innerText;
  const price = shopItem.getElementsByClassName('shop-item-price')[0].innerText.replace('$', '');
  const imageSrc = shopItem.getElementsByClassName('shop-item-image')[0].src;

  addItemToCart(title, price, imageSrc);
}

In the addToCartClicked function, we first get a reference to the button that was clicked using event.target. We then navigate to the parent elements to access the entire shop item.

Next, we retrieve the title, price, and image source of the shop item by accessing the corresponding elements and their inner text or src properties.

Finally, we call the addItemToCart function, passing the retrieved details as arguments.

Now that we have the item details, we can proceed to add a new row to the cart with those details.

First, let's define the addItemToCart function.

function addItemToCart(title, price, imageSrc) {
  const cartRow = document.createElement('div');
  cartRow.classList.add('cart-row');

  const cartItems = document.getElementsByClassName('cart-items')[0];
  const cartItemNames = cartItems.getElementsByClassName('cart-item-title');

  for (let i = 0; i < cartItemNames.length; i++) {
    if (cartItemNames[i].innerText === title) {
      alert('This item is already added to the cart.');
      return;
    }
  }

  const cartRowContents = `
    <div class="cart-item cart-column">
      <img class="cart-item-image" src="${imageSrc}" width="100" height="100">
      <span class="cart-item-title">${title}</span>
    </div>
    <span class="cart-price cart-column">$${price}</span>
    <div class="cart-quantity cart-column">
      <input class="cart-quantity-input" type="number" value="1">
      <button class="remove-button" type="button">Remove</button>
    </div>
  `;

  cartRow.innerHTML = cartRowContents;
  cartItems.appendChild(cartRow);

  cartRow.getElementsByClassName('remove-button')[0].addEventListener('click', removeCartItem);
  cartRow.getElementsByClassName('cart-quantity-input')[0].addEventListener('change', quantityChanged);

  updateCartTotal();
}

In the addItemToCart function, we first create a new div element to represent a new cart row. We add the appropriate class name (cart-row) to the cart row to style it accordingly.

Next, we check if the item being added is already present in the cart by comparing its title with the titles of existing cart items. If a match is found, we display an alert message and return from the function to prevent adding duplicate items to the cart.

If the item is not already in the cart, we proceed to create the inner contents of the cart row using a template string. We embed the item details passed as arguments into the template string to dynamically create the HTML markup.

After creating the cart row contents, we set the inner HTML of the cart row to the cartRowContents variable. This will populate the cart row with the correct item information.

Next, we append the cart row to the cartItems element to add it to the cart.

Finally, we add event listeners for the remove button and the quantity input of the new cart row. We also call the updateCartTotal function to recalculate the total price.

With this functionality in place, users can now add items to the cart, and the cart will dynamically update with the correct item details.

Removing Items from the Cart

Now that we have implemented the functionality to add items to the cart, let's add functionality to remove items from the cart. When a user clicks on the remove button of an item in the cart, it should be removed from the cart, and the total price should be updated accordingly.

To accomplish this, we will need to select all the remove buttons of the cart rows and add an event listener to each button. Inside the event listener function, we will remove the corresponding cart row and update the total price. Let's proceed with the implementation.

First, let's get a reference to all the remove buttons of the cart rows.

const removeButtons = document.getElementsByClassName('remove-button');

Next, let's loop over the remove buttons and add an event listener to each button.

for (let i = 0; i < removeButtons.length; i++) {
  const button = removeButtons[i];
  button.addEventListener('click', removeCartItem);
}

Now, let's define the removeCartItem function that will be called when a remove button is clicked.

function removeCartItem(event) {
  const buttonClicked = event.target;
  buttonClicked.parentElement.parentElement.remove();
  updateCartTotal();
}

In the removeCartItem function, we first get a reference to the remove button that was clicked using event.target. We then navigate to the parent elements to access the entire cart row and remove it from the DOM.

After removing the cart row, we call the updateCartTotal function to recalculate the total price.

Now, when a user clicks on the remove button of an item in the cart, it will be removed from the cart, and the total price will be updated accordingly.

Updating Quantity and Total

To provide a seamless user experience, let's allow users to update the quantity of items directly in the cart. When the quantity is updated, the total price should be recalculated and displayed accurately.

To accomplish this, we will add an event listener to each quantity input field in the cart. Whenever the quantity is changed, we will update the corresponding cart row's quantity and recalculate the total price. Let's proceed with the implementation.

First, let's get a reference to all the quantity input fields in the cart.

const quantityInputs = document.getElementsByClassName('cart-quantity-input');

Next, let's loop over the quantity inputs and add an event listener to each input field.

for (let i = 0; i < quantityInputs.length; i++) {
  const input = quantityInputs[i];
  input.addEventListener('change', quantityChanged);
}

Now, let's define the quantityChanged function that will be called when a quantity input field is changed.

function quantityChanged(event) {
  const input = event.target;

  if (isNaN(input.value) || input.value <= 0) {
    input.value = 1;
  }

  updateCartTotal();
}

In the quantityChanged function, we first get a reference to the quantity input field that was changed using event.target.

Next, we check if the input value is not a number (isNaN(input.value)) or if it is less than or equal to zero (input.value <= 0). If either condition is true, we set the input value to 1 to ensure that the user cannot enter a quantity less than 1.

After validating the input value, we call the updateCartTotal function to recalculate the total price.

Now, when a user updates the quantity of an item directly in the cart, the total price will be recalculated automatically.

Making a Purchase

Once the user has added all the desired items to the cart, they should be able to proceed to make a purchase. Let's add functionality to the purchase button that will display a confirmation message and remove all the items from the cart.

To accomplish this, we will add an event listener to the purchase button. When the button is clicked, a confirmation message will be displayed, and if the user confirms the purchase, all the cart items will be removed, and the total price will be reset to zero. Let's proceed with the implementation.

First, let's get a reference to the purchase button.

const purchaseButton = document.getElementsByClassName('purchase-button')[0];

Next, let's add an event listener to the purchase button.

purchaseButton.addEventListener('click', purchaseClicked);

Now, let's define the purchaseClicked function that will be called when the purchase button is clicked.

function purchaseClicked() {
  alert('Thank you for your purchase.');

  const cartItems = document.getElementsByClassName('cart-items')[0];
  while (cartItems.hasChildNodes()) {
    cartItems.removeChild(cartItems.firstChild);
  }

  updateCartTotal();
}

In the purchaseClicked function, we first display an alert message to thank the user for their purchase.

Next, we get a reference to the cartItems element, which contains all the cart rows. We then use a while loop to remove all the child nodes (cart rows) from the cartItems element until there are no more child nodes remaining.

After removing all the cart rows, we call the updateCartTotal function to recalculate the total price.

Now, when the purchase button is clicked, a confirmation message will be displayed, and if the user confirms the purchase, all the items will be removed from the cart, and the total price will be reset to zero.

Cleaning Up the Code

In this step, we will clean up our JavaScript code to ensure it is well-structured and follows best practices. We will remove any unnecessary code and comments to improve readability and maintainability.

// Add your JavaScript code here

Conclusion

Congratulations! You have successfully created a fully functional shopping cart using vanilla JavaScript. You have learned how to set up the project, add functionality to remove and add items to the cart, update quantity and total, and make a purchase. This shopping cart can be integrated into your own website to enhance the user experience for your customers.

Thank you for following along with this tutorial. If you have any questions or feedback, please let us know in the comments. Happy coding!

I am an ordinary seo worker. My job is seo writing. After contacting Proseoai, I became a professional seo user. I learned a lot about seo on Proseoai. And mastered the content of seo link building. Now, I am very confident in handling my seo work. Thanks to Proseoai, I would recommend it to everyone I know. — Jean

Browse More Content