Add To Cart Shopping Using Html Css And Javascript

8 min read Jun 22, 2024
Add To Cart Shopping Using Html Css And Javascript

Add to Cart Functionality with HTML, CSS, and JavaScript

This article will guide you through creating a basic "Add to Cart" functionality using HTML, CSS, and JavaScript. We'll create a simple e-commerce page with products, a shopping cart, and the ability to add items to the cart and view their details.

1. HTML Structure

First, we'll set up the HTML structure for our e-commerce page.




    
    
    Shopping Cart Example
    


    

Products

Product 1

Product 1

Description of product 1

Shopping Cart

Product Price Quantity Subtotal Action
Total: $0

In this structure:

  • We have a container div to hold our products and cart sections.
  • products div will contain the product listings.
  • Each product div represents a single product with an image, title, description, and an "Add to Cart" button.
  • cart div holds the shopping cart table and total amount.
  • We include style.css for styling and script.js for JavaScript functionality.

2. CSS Styling (style.css)

We'll add basic styling for the layout and appearance. You can customize this according to your preferences.

body {
    font-family: sans-serif;
    display: flex;
    justify-content: space-around;
    padding: 20px;
}

.products, .cart {
    width: 45%;
    border: 1px solid #ddd;
    padding: 20px;
}

.product {
    margin-bottom: 20px;
    border: 1px solid #ddd;
    padding: 10px;
}

.product img {
    width: 100px;
    height: 100px;
}

table {
    width: 100%;
    border-collapse: collapse;
}

th, td {
    border: 1px solid #ddd;
    padding: 8px;
}

.add-to-cart {
    padding: 8px 15px;
    background-color: #4CAF50;
    color: white;
    border: none;
    cursor: pointer;
}

.total {
    margin-top: 20px;
    font-size: 18px;
}

This CSS provides simple styles for the products, cart table, buttons, and total amount display.

3. JavaScript Functionality (script.js)

Now, we'll add JavaScript to handle the "Add to Cart" functionality and cart management.

const cart = [];
const cartTable = document.getElementById('cart-table').getElementsByTagName('tbody')[0];
const cartTotal = document.getElementById('cart-total');

function addToCart(productId) {
  const product = document.getElementById(productId);
  const productName = product.querySelector('h3').textContent;
  const productPrice = 10; // Replace with actual product price

  const existingItem = cart.find(item => item.id === productId);
  if (existingItem) {
    existingItem.quantity++;
  } else {
    cart.push({ id: productId, name: productName, price: productPrice, quantity: 1 });
  }
  updateCart();
}

function updateCart() {
  cartTable.innerHTML = '';
  let total = 0;
  cart.forEach(item => {
    const row = cartTable.insertRow();
    const nameCell = row.insertCell();
    const priceCell = row.insertCell();
    const quantityCell = row.insertCell();
    const subtotalCell = row.insertCell();
    const actionCell = row.insertCell();

    nameCell.textContent = item.name;
    priceCell.textContent = item.price;
    quantityCell.textContent = item.quantity;
    subtotalCell.textContent = (item.price * item.quantity).toFixed(2);
    total += item.price * item.quantity;

    // Add "Remove" button to each row
    const removeButton = document.createElement('button');
    removeButton.textContent = 'Remove';
    removeButton.addEventListener('click', () => {
      const index = cart.findIndex(i => i.id === item.id);
      if (index !== -1) {
        cart.splice(index, 1);
        updateCart();
      }
    });
    actionCell.appendChild(removeButton);
  });
  cartTotal.textContent = total.toFixed(2);
}

// Attach event listeners to "Add to Cart" buttons
const addToCartButtons = document.querySelectorAll('.add-to-cart');
addToCartButtons.forEach(button => {
  button.addEventListener('click', () => {
    addToCart(button.dataset.productId);
  });
});

This JavaScript code:

  • Creates an empty cart array to store cart items.
  • Defines functions addToCart and updateCart.
  • addToCart adds a product to the cart or increments its quantity if it already exists.
  • updateCart updates the cart table and total amount display.
  • Attaches event listeners to all "Add to Cart" buttons to call addToCart when clicked.

4. Integrating with Existing Product Data

The code above uses a placeholder product price. In a real application, you would replace this with actual product data fetched from your database or API.

Example:

// Assuming you have product data in an array
const products = [
  { id: 'product1', name: 'Product 1', price: 15.99, description: 'Product 1 Description' },
  { id: 'product2', name: 'Product 2', price: 29.99, description: 'Product 2 Description' },
  // ... more products
];

// Dynamically create product divs using the product data
products.forEach(product => {
  // ... create HTML for the product div ...
  // Set product name, price, and description using the product object
});

This way, you can dynamically create product elements from your product data.

5. Conclusion

This guide provides a basic implementation of "Add to Cart" functionality using HTML, CSS, and JavaScript. You can build upon this foundation by adding features like:

  • Product details modal: Display detailed information about a product when it's clicked.
  • Quantity selection: Allow users to choose the quantity of an item before adding to the cart.
  • Checkout process: Implement a checkout process with payment gateway integration.

Remember to customize the styling, functionality, and integrate with your specific product data to create a fully functional e-commerce experience.

Latest Posts