Creating an E-commerce Product Filter with JavaScript


An ecommerce product filter in JavaScript is a front-end development technique used to allow users to filter and sort through a large number of products on an ecommerce website. This filter enables users to refine their search based on specific criteria, such as price range, brand, size, color, and more.

Using JavaScript, an ecommerce website can implement a product filter that dynamically updates the product list based on user-selected filters. When a user selects a filter option, JavaScript can filter the products on the webpage and display only the products that match the selected criteria.

Moreover, the JavaScript-based product filter can also include a search bar, which allows users to search for specific products by name, description, or keyword. This search feature can also be combined with filters to provide users with highly personalized and targeted results.

Overall, an ecommerce product filter in JavaScript is a powerful tool for improving the user experience of an ecommerce website by enabling users to quickly find the products they need and make informed purchase decisions.

Source Code

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="css/style.css" />
  </head>
  <body>
    <div class="container">
      <div class="sidebar">
        <div class="logo">Joes Kart</div>
        <input type="text" id="txtSearch" placeholder="Search Product..." />
        <h3>Category</h3>
        <ul class="category-list">

        </ul>
        <h3>Price Range</h3>
        <div class="price">
          <input type="range" id="priceRange" />
          <span class="priceValue">500</span>
        </div>
      </div>
      <div class="content">
        <div class="products"></div>
      </div>
    </div>
    <script src="js/script.js"></script>
  </body>
</html>

This is a code that displays a list of products and allows users to filter the list by category and price range using JavaScript.

js/script.js

const data = [
  {
    id: 1,
    name: "Fire Boltt Ninja 2",
    img: "https://m.media-amazon.com/images/I/617eiZeFtNL._SL1500_.jpg",
    amt: 1599,
    seller: "Boltt Store",
    catagory: "Watch",
  },

  {
    id: 2,
    name: "Noise Pulse Go",
    img: "https://m.media-amazon.com/images/I/61akt30bJsL._SL1500_.jpg",
    amt: 1300,
    seller: "Noise Store",
    catagory: "Watch",
  },

  {
    id: 3,
    name: "boAt Xtend Pro",
    img: "https://m.media-amazon.com/images/I/61ZuL8CUigL._SL1500_.jpg",
    amt: 2799,
    seller: "Rajesh Watchs",
    catagory: "Watch",
  },
  {
    id: 4,
    name: "Lenovo Tab M8",
    img: "https://m.media-amazon.com/images/I/71SvqTFPXJL._SL1500_.jpg",
    amt: 9270,
    seller: "Stonehenge Retail",
    catagory: "Tablets",
  },
  {
    id: 5,
    name: "Honor PAD X8",
    img: "https://m.media-amazon.com/images/I/710G-VKcgtL._SL1500_.jpg",
    amt: 12999,
    seller: "Honor india",
    catagory: "Tablets",
  },

  {
    id: 6,
    name: "IKALL N9 ",
    img: "https://m.media-amazon.com/images/I/7185GL6hPlL._SL1500_.jpg",
    amt: 3999,
    seller: "IKALL Store",
    catagory: "Tablets",
  },

  {
    id: 7,
    name: "Oppo Pad Air",
    img: "https://m.media-amazon.com/images/I/513FD4w8hGL._SL1500_.jpg",
    amt: 15999,
    seller: "Oppo Store",
    catagory: "Tablets",
  },
  {
    id: 8,
    name: "Acer EK220Q",
    img: "https://m.media-amazon.com/images/I/8150iUXkc5L._SL1500_.jpg",
    amt: 6249,
    seller: "Accer Store",
    catagory: "Monitors",
  },
  {
    id: 9,
    name: "Samsung 24",
    img: "https://m.media-amazon.com/images/I/81TjRLHaz1L._SL1500_.jpg",
    amt: 9799,
    seller: "Samsung Store",
    catagory: "Monitors",
  },

  {
    id: 10,
    name: "ZEBRONICS AC32FHD ",
    img: "https://m.media-amazon.com/images/I/813Y1TIZwfL._SL1500_.jpg",
    amt: 12799,
    seller: "ZEBRONICS Store",
    catagory: "Monitors",
  },
];

const productsContainer = document.querySelector(".products");
const categoryList = document.querySelector(".category-list");

function displayProducts(products) {
  if (products.length > 0) {
    const product_details = products
      .map(
        (product) => `
  <div class="product">
  <div class="img">
    <img src="${product.img}" alt="${product.name}" />
  </div>
  <div class="product-details">
    <span class="name">${product.name}</span>
    <span class="amt">Rs.${product.amt}</span>
    <span class="seller">${product.seller}</span>
  </div>
</div>`
      )
      .join("");

    productsContainer.innerHTML = product_details;
  } else {
    productsContainer.innerHTML = "<h3>No Products Available</h3>";
  }
}

function setCategories() {
  const allCategories = data.map((product) => product.catagory);
  //console.log(allCategories);
  const catagories = [
    "All",
    ...allCategories.filter((product, index) => {
      return allCategories.indexOf(product) === index;
    }),
  ];
  //console.log(catagories);
  categoryList.innerHTML = catagories.map((catagory) => `<li>${catagory}</li>`).join("");

  categoryList.addEventListener("click", (e) => {
    const selectedCatagory = e.target.textContent;
    selectedCatagory === "All" ? displayProducts(data) : displayProducts(data.filter((product) => product.catagory == selectedCatagory));
  });
}
const priceRange = document.querySelector("#priceRange");
const priceValue = document.querySelector(".priceValue");

function setPrices() {
  const priceList = data.map((product) => product.amt);
  const minPrice = Math.min(...priceList);
  const maxPrice = Math.max(...priceList);
  priceRange.min = minPrice;
  priceRange.max = maxPrice;
  priceValue.textContent = "Rs." + maxPrice;

  priceRange.addEventListener("input", (e) => {
    priceValue.textContent = "Rs." + e.target.value;
    displayProducts(data.filter((product) => product.amt <= e.target.value));
  });
}

const txtSearch = document.querySelector("#txtSearch");
txtSearch.addEventListener("keyup", (e) => {
  const value = e.target.value.toLowerCase().trim();
  if (value) {
    displayProducts(data.filter((product) => product.name.toLowerCase().indexOf(value) !== -1));
  } else {
    displayProducts(data);
  }
});

displayProducts(data);
setCategories();
setPrices();

First, the list of products is defined as an array of objects, where each object contains details about a particular product such as its name, image, price, seller, and category.

Next, the displayProducts function is defined which takes an array of products as an argument and generates HTML markup to display the product information in the DOM. If there are no products available, it displays a message indicating so.

The setCategories function generates a list of categories by extracting all the categories from the list of products and filtering out duplicates. It then generates HTML markup for a list of categories and adds an event listener to the list items. When a category is clicked, it filters the products by the selected category and calls the displayProducts function to update the DOM.

The setPrices function sets up a price range input element and a corresponding display element. It extracts the minimum and maximum price from the list of products, sets the minimum and maximum values of the price range input element, and sets the initial value of the display element to the maximum price. It then adds an event listener to the price range input element to filter the products by the selected price range and call the displayProducts function to update the DOM.

Finally, these functions are called to set up the initial display of the list of products, categories, and price range.

css/style.css

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@100;300;400;500;600;700;800&display=swap");

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

body {
  background-color: #353b48;
}
.container {
  background-color: #fff;
  width: 95%;
  margin: 0 auto;
  min-height: 1000px;
  display: flex;
}

.sidebar {
  flex: 1;
  background-color: #f5f6fa;
  padding: 10px;
}
.logo {
  font-weight: 800;
  font-size: 20px;
  text-transform: uppercase;
  color: #e74c3c;
  margin-bottom: 10px;
}
.sidebar input[type="text"] {
  padding: 5px 5px;
  outline: none;
  width: 100%;
  margin-bottom: 15px;
}
.sidebar h3 {
  font-weight: 600;
  margin-bottom: 10px;
}
.sidebar ul {
  list-style: none;
}
.sidebar ul li {
  margin: 5px 0;
  padding-left: 5px;
  cursor: pointer;
}
.sidebar ul li:hover {
  background-color: #dcdde1;
}
.content {
  flex: 4;
}

.products {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  padding: 10px;
  gap: 10px;
  cursor: pointer;
}
.product {
  width: 250px;
  display: flex;
  flex-direction: column;
  box-shadow: rgba(99, 99, 99, 0.2) 0px 2px 8px 0px;
  overflow: hidden;
}

.product .img {
  flex: 1;
}
.product .img img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  transition: 0.5s;
  transform: scale(0.75);
}
.product:hover img {
  transform: scale(1);
}
.product .product-details {
  padding: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.product-details span:nth-child(1) {
  color: #e74c3c;
  font-weight: 600;
}

.product-details span:nth-child(2) {
  color: #2980b9;
  font-weight: 600;
}

.product-details span:nth-child(3) {
  font-size: 11px;
  font-weight: 600;
  color: #16a085;
}

Output

Product Filter

Live Preview


List of Programs


JS Practical Questions & Answers


JS Practical Project