E-commerce
Creating a Shopping Cart with Vanilla JavaScript: A Beginners Guide
Creating a Shopping Cart with Vanilla JavaScript: A Beginner's Guide
In this comprehensive guide, we will walk you through the process of creating a functional shopping cart using only Vanilla JavaScript. We'll cover the basics, including creating the HTML structure, implementing JavaScript logic, and adding additional features. By the end, you'll have a fully functional shopping cart ready for integration into your website.
Step 1: HTML Structure
First, let's create a basic HTML structure for our shopping cart. This will include a list of products, an add-to-cart button for each product, and a display area for the cart contents and total price.
!DOCTYPE html html langen head meta charsetUTF-8/ meta nameviewport contentwidthdevice-width, initial-scale1.0/ titleShopping Cart/title style .cart { border: 1px solid #ccc; padding: 10px; width: 300px; } .item { margin: 5px 0; } /style /head body h1Shopping Cart/h1 div idcart-area div classitem spanProduct 1 - $10/span button classadd-to-cart data-productProduct 1 data-price10Add to Cart/button /div div classitem spanProduct 2 - $20/span button classadd-to-cart data-productProduct 2 data-price20Add to Cart/button /div div classitem spanProduct 3 - $30/span button classadd-to-cart data-productProduct 3 data-price30Add to Cart/button /div /div div classcart h2Your Cart/h2 ul idcart-items/ul pTotal: span idtotal-price/span/p /div script srccart.js/script /body /html
Step 2: JavaScript Logic
Next, we'll create the JavaScript logic to manage the cart. This includes initializing the cart array, updating the cart display, and handling user interactions.
script // Initialize cart array and total price let cart []; let totalPrice 0; // Function to update the cart display function updateCart() { const cartItems (#39;cart-items#39;); const totalPriceElement (#39;total-price#39;); // Clear current cart items #39;#39;; // Add each item in the cart to the display for (let item of cart) { const li (#39;li#39;); li.textContent `Product - $${item}`; (li); } // Update total price totalPriceElement.textContent `$${totalPrice}`; } // Function to add an item to the cart function addToCart(product, price) { cart.push({ product, price }); totalPrice price; updateCart(); } // Event listener for Add to cart buttons const addButtons document.querySelectorAll(#39;.add-to-cart#39;); (button { (#39;click#39;, event { const product (#39;data-product#39;); const price parseFloat((#39;data-price#39;)); addToCart(product, price); }); }); /script
Step 3: Test Your Shopping Cart
After writing the code, open the HTML file in a web browser. You should see the products listed and an option to add each product to the cart. The cart will update in real-time, showing both the individual items and the total price.
Additional Features
Now that you have a working shopping cart, you can extend its functionality by adding the following features:
Removing Items from the Cart
Allow users to remove items from the cart by adding a remove button or implementing a control in the cart display.
Example:
div classitem spanProduct 1 - $10/span button classadd-to-cart data-productProduct 1 data-price10Add to Cart/button button classremove-from-cart data-productProduct 1Remove/button /div
script // Function to remove an item from the cart function removeFromCart(product) { cart (item ! product); totalPrice - (item product).price; updateCart(); } // Event listener for Remove buttons const removeButtons document.querySelectorAll(#39;.remove-from-cart#39;); (button { (#39;click#39;, event { const product (#39;data-product#39;); removeFromCart(product); }); }); /script
Persisting the Cart State Using Local Storage
Store the cart state using local storage so that users can return to the cart with the same items after refreshing the page or navigating away.
script (#39;DOMContentLoaded#39;, () { // Load cart state from local storage const savedCart (#39;cart#39;); if (savedCart) { cart (savedCart); (item { addToCart(, ); }); } // Save cart state to local storage updateCart(); (#39;cart#39;, (cart)); }); /script
Adding Quantity Controls for Each Product
Allow users to adjust the quantity of each product in the cart.
Example:
div classitem spanProduct 1 - $10 x input typenumber min1 max10 value1 //span button classadd-to-cart data-productProduct 1 data-price10Add to Cart/button /div
script // Function to add quantity to cart function addToCartWithQuantity(product, price, quantity) { for (let i 0; i
Implementing a Checkout Process
Develop a checkout process that guides users through the steps to complete a purchase, such as entering shipping information and payment details.
Example:
Shipping Address Payment Method Confirmation PageConclusion
By following this guide, you have now created a functional shopping cart using Vanilla JavaScript. You can further enhance its functionality by adding more advanced features. Remember to test your cart thoroughly to ensure a smooth user experience.