Skip to main content

How to create a simple shopping project using HTML, CSS and JavaScript?


 Below is the complete shopping project with all necessary features are required.

Let's follow the step by step process:

index. html page code:

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Online Shop</title>

  <link rel="stylesheet" href="style.css">

</head>

<body>

  <!-- Header -->

  <header class="header">

    <div class="logo">ShopLogo</div>

    <nav class="nav">

      <a href="#">Home</a>

      <a href="#products">Products</a>

      <a href="#cart">Cart</a>

      <a href="#contact">Contact</a>

    </nav>

  </header>


  <!-- Hero Section -->

  <section class="hero">

    <h1>Welcome to Our Shop</h1>

    <p>Find the best deals on your favorite products!</p>

    <button class="shop-now">Shop Now</button>

  </section>


  <!-- Filters -->

  <section class="filters">

    <div class="filter">

      <label for="category">Category:</label>

      <select id="category">

        <option value="all">All</option>

        <option value="electronics">Electronics</option>

        <option value="clothing">Clothing</option>

        <option value="accessories">Accessories</option>

      </select>

    </div>

    <div class="filter">

      <label for="sort">Sort By:</label>

      <select id="sort">

        <option value="default">Default</option>

        <option value="price-asc">Price: Low to High</option>

        <option value="price-desc">Price: High to Low</option>

      </select>

    </div>

    <div class="filter">

      <label for="search">Search:</label>

      <input type="text" id="search" placeholder="Search products">

    </div>

  </section>


  <!-- Product Section -->

  <section class="products" id="products">

    <div class="product-grid">

      <!-- Products dynamically generated -->

    </div>

  </section>


  <!-- Cart Section -->

  <section class="cart" id="cart">

    <h2>Your Cart</h2>

    <div class="cart-items">

      <p>No items in your cart.</p>

    </div>

    <div class="cart-summary">

      <p>Total Items: <span id="total-items">0</span></p>

      <p>Total Price: $<span id="total-price">0.00</span></p>

    </div>

  </section>


  <!-- Footer -->

  <footer class="footer">

    <p>© 2024 Online Shop. All rights reserved.</p>

    <p>Follow us: <a href="#">Facebook</a> | <a href="#">Twitter</a></p>

  </footer>


  <script src="main.js"></script>

</body>

</html>


style. css page code

*{
margin:0;
padding: 0;
box-sizing: border-box;
font-family: sans-serif;
}


body{
font-family: sans-serif;
line-height: 1.6;
color:#333;
}

.header{
display: flex;
justify-content: space-between;
align-items: center;
padding:10px 20px;
background-color:#333;
color: white;
}

.header .logo{
font-size: 1.5em;
font-weight: bold;
}

.header .nav{
display: flex;
font-weight: bold;

}

.header .nav a{
color: white;
text-decoration: none;
font-size: 1em;
padding:0 10px;
}

.header .nav a:hover{
text-decoration: underline;
}

.hero{
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
padding: 50px 20px;
background-color: #f4f4f4;
}

.hero h1{
font-size: 2.5em;
margin-bottom: 10px;
}

.hero{
font-size: 1.2em;
margin-bottom: 20px;

}

.hero .shop-now{
padding:10px 20px;
background-color: #333;
color: white;
border: none;
font-size: 1em;
cursor: pointer;
}

.hero .shop-now:hover{
background-color: #555;
}

.products{
padding: 40px 20px;
}
.products h2{
text-align: center;
margin-bottom: 20px;
font-size: 2em;
}

.filters{
display: flex;
justify-content: space-between;
margin-bottom:20px;
}

.filters .filter{
flex: 1;
display: flex;
align-items: center;
gap:20px;
justify-content: center;


}

.product-grid{
display: flex;
flex-wrap: wrap;
gap:20px;
justify-content: center;
}

.product{
flex: 1 1 calc(25% - 20px);
background-color: #f9f9f9;
padding:15px;
border: 1px solid #dddd;
text-align: center;
transition:transform 0.3s ease box-shadow 0.3s ease;

}

.product:hover{
transform: scale(1.05);
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.product img{
max-width: 100%;
margin-bottom: 10px;


}

.product h3{
font-size:1.2em;
margin-bottom:5px;

}

.product p{
font-size: 1em;
margin-bottom: 10px;
}

.product button{
padding:10px 15px;
background-color:#333;
color: white;
border: none;
font-size: 1em;
cursor: pointer;
}

.product button:hover{
background-color: #555;

}

.cart{
padding: 20px;
background-color: #f9f9f9;
}

.cart h2{
text-align: center;
}

.cart-item{
margin-top: 20px;

}

.cart-summary{
margin-top:20px;
text-align: center;
}

.cart-item{
display: flex;
justify-content: space-between;
margin-bottom: 10px;
}

.cart-item button{
background-color: red;
color: white;
border: none;
padding: 5px 10px;
cursor: pointer;
}

.footer{
width:100%;
height:200px;
background-color: black;
color: white;
text-align: center;
}


main. js page code


// Mock Product Data
const products = [
  { id: 1, name: "Smartphone", price: 299.99, category: "electronics", image: "https://via.placeholder.com/150" },
  { id: 2, name: "Headphones", price: 49.99, category: "electronics", image: "https://via.placeholder.com/150" },
  { id: 3, name: "T-Shirt", price: 19.99, category: "clothing", image: "https://via.placeholder.com/150" },
  { id: 4, name: "Sunglasses", price: 99.99, category: "accessories", image: "https://via.placeholder.com/150" },
  { id: 5, name: "Jeans", price: 39.99, category: "clothing", image: "https://via.placeholder.com/150" },
  { id: 6, name: "Smartwatch", price: 199.99, category: "electronics", image: "https://via.placeholder.com/150" },
];

let cart = [];

// Function to render products dynamically
function renderProducts(category = "all", sort = "default", search = "") {
  const productGrid = document.querySelector(".product-grid");
  productGrid.innerHTML = "";

  let filteredProducts = products;

  if (category !== "all") {
    filteredProducts = filteredProducts.filter(p => p.category === category);
  }

  if (search) {
    filteredProducts = filteredProducts.filter(p =>
      p.name.toLowerCase().includes(search.toLowerCase())
    );
  }

  if (sort === "price-asc") {
    filteredProducts.sort((a, b) => a.price - b.price);
  } else if (sort === "price-desc") {
    filteredProducts.sort((a, b) => b.price - a.price);
  }

  if (filteredProducts.length === 0) {
    productGrid.innerHTML = "<p>No products found.</p>";
    return;
  }

  filteredProducts.forEach(product => {
    const productCard = document.createElement("div");
    productCard.classList.add("product");
    productCard.innerHTML = `
      <img src="${product.image}" alt="${product.name}">
      <h3>${product.name}</h3>
      <p>$${product.price.toFixed(2)}</p>
      <button onclick="addToCart(${product.id})">Add to Cart</button>
    `;
    productGrid.appendChild(productCard);
  });
}

// Function to handle adding a product to the cart
function addToCart(productId) {
  const product = products.find(p => p.id === productId);
  const cartItem = cart.find(item => item.id === productId);

  if (cartItem) {
    cartItem.quantity += 1;
  } else {
    cart.push({ ...product, quantity: 1 });
  }

  updateCart();
}

// Function to handle removing a product from the cart
function removeFromCart(productId) {
  cart = cart.filter(item => item.id !== productId);
  updateCart();
}

// Function to update the cart display
function updateCart() {
  const cartItems = document.querySelector(".cart-items");
  const totalItems = document.getElementById("total-items");
  const totalPrice = document.getElementById("total-price");

  cartItems.innerHTML = '';

  if (cart.length === 0) {
    cartItems.innerHTML = "<p>No items in your cart.</p>";
  } else {
    cart.forEach(item => {
      const cartItem = document.createElement("div");
      cartItem.classList.add("cart-item");
      cartItem.innerHTML = `
        <p>${item.name} (x${item.quantity}) - $${(item.price * item.quantity).toFixed(2)}</p>
        <button onclick="removeFromCart(${item.id})">Remove</button>
      `;
      cartItems.appendChild(cartItem);
    });
  }

  totalItems.textContent = cart.reduce((total, item) => total + item.quantity, 0);
  totalPrice.textContent = cart.reduce((total, item) => total + item.price * item.quantity, 0).toFixed(2);
}

// Event listeners for filters and search
document.getElementById("category").addEventListener("change", event => {
  const category = event.target.value;
  const sort = document.getElementById("sort").value;
  const search = document.getElementById("search").value;
  renderProducts(category, sort, search);
});

document.getElementById("sort").addEventListener("change", event => {
  const sort = event.target.value;
  const category = document.getElementById("category").value;
  const search = document.getElementById("search").value;
  renderProducts(category, sort, search);
});

document.getElementById("search").addEventListener("input", event => {
  const search = event.target.value;
  const category = document.getElementById("category").value;
  const sort = document.getElementById("sort").value;
  renderProducts(category, sort, search);
});

// Initial render of products
renderProducts();





Download source code link 🔗

Download





Comments

Popular posts from this blog

Microsoft Excel top functions.

  Microsoft Excel offers numerous functions to simplify data analysis and calculation. Here are some of the most commonly used and powerful functions: Basic Functions SUM : Adds values. =SUM(A1:A10) AVERAGE : Calculates the mean of numbers. =AVERAGE(A1:A10) IF : Performs logical tests and returns values based on conditions. =IF(A1>10, "Yes", "No") COUNT : Counts numeric values in a range. =COUNT(A1:A10) LEN : Returns the length of a text string. =LEN(A1) Lookup and Reference Functions VLOOKUP : Looks for a value in the first column and returns a value in the same row from another column. =VLOOKUP(lookup_value, table_array, col_index_num, [range_lookup]) HLOOKUP : Similar to Here are practical examples of common Excel functions and how they can be applied in real-life scenarios: 1. SUM Scenario: Calculate the total sales for a week. Example: A B Day Sales Monday 200 Tuesday 150 Wednesday 300 Thursday 250 Friday 100 ...

Creating Wages Sheet using Microsoft Excel

  Creating wages sheet using Microsoft Excel The DAYS360 function in Microsoft Excel calculates the number of days between two dates based on a 360-day year (commonly used in financial calculations). A 360-day year assumes each month has 30 days, simplifying interest and payment schedules. Syntax: DAYS360(start_date, end_date, [method]) Parameters: start_date : The starting date (required). Enter it as a valid date or reference a cell containing a date. end_date : The ending date (required). Enter it similarly to the start_date. method : Logical value (optional). FALSE (default): Uses the U.S. (NASD) method for date calculations. TRUE : Uses the European method. Key Differences Between Methods: U.S. (NASD) : Adjusts the start and end dates depending on whether they fall on the 31st of a month. European : Always treats the start and end dates as the 30th of the month if they are the 31st. Example Usage: Example 1: Calculate days using the U.S. method =DAYS360("01/01/2024", ...

How to use Microsoft Excel PMT function?

  To use the PMT function in Microsoft Excel, follow these steps: Steps to Use the PMT Function: Open Excel : Open your Excel workbook where you want to calculate the payment. Select a Cell : Click on the cell where you want the result (monthly payment). Enter the PMT Function : Use the formula syntax: =PMT(rate, nper, pv, [fv], [type]) Input Arguments : rate : Interest rate per period (e.g., for a monthly rate, divide the annual rate by 12). nper : Total number of payment periods. pv : Present value (loan amount or investment). fv (optional) : Future value, usually 0 for loans. type (optional) : Payment timing: 0 (default): End of the period. 1: Beginning of the period. Press Enter : Excel will calculate and display the periodic payment. Example 1: Monthly Loan Payment Problem: You take a loan of $15,000 with an annual interest rate of 5%, to be repaid over 3 years (36 months). What is the monthly payment? Steps: Select a cell and enter: =PMT(5%/12, 3*12, -...