Implementing Product Filtering with HTML, TailwindCSS, and JavaScript

Faraz

By Faraz -

Learn how to enhance user experience with interactive product filtering using HTML, TailwindCSS, and JavaScript. Beginner-friendly tutorial inside!


Implementing Product Filtering with HTML, TailwindCSS, and JavaScript.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Preview
  6. Conclusion

In the world of online shopping, providing a seamless and intuitive user experience is key to keeping visitors engaged and converting them into customers. One powerful way to enhance user experience on an e-commerce website is by implementing product filtering functionality. Product filtering allows users to narrow down their search results based on specific criteria, such as price range, size, color, or any other relevant attribute.

In this comprehensive tutorial, we'll explore how to implement product filtering using a combination of HTML, TailwindCSS, and JavaScript. Whether you're a beginner looking to add basic filtering options to your website or an experienced developer aiming to create a more interactive filtering experience, this guide will walk you through the process step by step.

By the end of this tutorial, you'll have the skills and knowledge to create dynamic and user-friendly product filtering systems that enhance navigation, improve user satisfaction, and ultimately drive more sales on your e-commerce website. So let's dive in and learn how to take your website's filtering capabilities to the next level!

Source Code

Step 1 (HTML Code):

Begin by structuring your HTML code to accommodate the filtering options. Use semantic HTML elements for better accessibility and SEO.

Let's break down the HTML Code:

1. <!DOCTYPE html>: Defines the document type and version of HTML being used.

2. <html lang="en">: Defines the root element of the HTML document and specifies the language as English.

3. <head>: Contains meta-information about the HTML document, such as character encoding, viewport settings, and external scripts.

  • <meta charset="UTF-8" />: Specifies the character encoding of the document as UTF-8.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0" />: Sets the viewport properties for responsive design.
  • <script src="https://cdn.tailwindcss.com"></script>: Imports the Tailwind CSS framework for styling.
  • <title>Product Filtering</title>: Sets the title of the webpage to "Product Filtering".

4. <body class="bg-gray-800 text-white">: Represents the body of the HTML document with a background color of gray and white text color.

5. <nav class="bg-gray-900 p-4 mb-6">: Defines a navigation bar with a dark gray background and padding.

6. <div class="container max-w-6xl mx-auto flex flex-col sm:flex-row gap-8 items-center">: Contains navigation elements and aligns them horizontally.

  • Search area: Includes an input field for searching products with an icon.
  • Cart icon: Displays a shopping cart icon with a count badge indicating the number of items in the cart.

7. <main class="flex flex-col md:flex-row container mx-auto max-w-6xl">: Defines the main content area with a container for responsive layout.

  • Filters section: Displays a list of checkboxes for filtering products by category.
  • Products wrapper: Placeholder for displaying products dynamically.

8. <script src="/script.js"></script>: Links an external JavaScript file named "script.js" for dynamic functionality, such as handling user interactions and updating the webpage content.

Step 2 (CSS Code):

No custom CSS thanks to Tailwind!

/*

 No custom CSS thanks to Tailwind!
 tailwindcss.com

*/ 

Step 3 (JavaScript Code):

Utilize JavaScript to handle user interactions and dynamically update the displayed products based on selected filters. Implement event listeners and functions to manage filtering logic efficiently.

Let's break it down step by step:

1. Product Data: The code starts with an array called products, containing objects representing various products. Each product object includes properties like name, image URL, category, and price.

2. DOM Elements: The code then retrieves various DOM elements using document.getElementById and document.querySelectorAll. These elements include a container for products, checkboxes for filtering by category, a container for filters, a search input field, a cart button, and an element to display the count of items in the cart.

3. Initializing Variables: cartItemCount is initialized to keep track of the number of items in the cart.

4. Creating Product Elements: The code iterates over the product array using forEach and creates HTML elements to represent each product. It calls the createProductElement function for each product, which creates a div element with the product image, name, price, and an "Add to Cart" button. These elements are then appended to the productsWrapper.

5. Adding Event Listeners: Event listeners are added to the filters (checkboxes) and the search input field to trigger the filterProducts function whenever there is a change.

6. Creating Product Element Function: The createProductElement function takes a product object as input and creates a div element representing that product with its details and an "Add to Cart" button. The event listener for the "Add to Cart" button is also attached here.

7. Updating Cart: The updateCart function toggles the "Add to Cart"/"Remove From Cart" button text and background color based on whether the item is added to the cart or not. It also updates the cartItemCount accordingly and updates the cart count display.

8. Filtering Products: The filterProducts function is called whenever there is a change in the search input or the selected checkboxes. It filters the products based on the search term and selected categories, and hides/shows the product elements accordingly by adding/removing the 'hidden' class.

const products = [
  {
    name: 'Sony Playstation 5',
    url: 'https://i.ibb.co/zHmZnWx/playstation-5.png',
    category: 'games',
    price: 499.99,
  },
  {
    name: 'Samsung Galaxy',
    url: 'https://i.ibb.co/rFFMDH7/samsung-galaxy.png',
    category: 'smartphones',
    price: 399.99,
  },
  {
    name: 'Cannon EOS Camera',
    url: 'https://i.ibb.co/mhm1hLq/cannon-eos-camera.png',
    category: 'cameras',
    price: 749.99,
  },
  {
    name: 'Sony A7 Camera',
    url: 'https://i.ibb.co/LS9TDLN/sony-a7-camera.png',
    category: 'cameras',
    price: 1999.99,
  },
  {
    name: 'LG TV',
    url: 'https://i.ibb.co/QHgFnHk/lg-tv.png',
    category: 'televisions',
    price: 799.99,
  },
  {
    name: 'Nintendo Switch',
    url: 'https://i.ibb.co/L0L9SdG/nintendo-switch.png',
    category: 'games',
    price: 299.99,
  },
  {
    name: 'Xbox Series X',
    url: 'https://i.ibb.co/C8rBVdT/xbox-series-x.png',
    category: 'games',
    price: 499.99,
  },
  {
    name: 'Samsung TV',
    url: 'https://i.ibb.co/Pj1nm4B/samsung-tv.png',
    category: 'televisions',
    price: 1099.99,
  },
  {
    name: 'Google Pixel',
    url: 'https://i.ibb.co/5F58zmH/google-pixel.png',
    category: 'smartphones',
    price: 499.99,
  },
  {
    name: 'Sony ZV1F Camera',
    url: 'https://i.ibb.co/5Wy3RZ9/sony-zv1f-camera.png',
    category: 'cameras',
    price: 799.99,
  },
  {
    name: 'Toshiba TV',
    url: 'https://i.ibb.co/FxM6rXq/toshiba-tv.png',
    category: 'televisions',
    price: 499.99,
  },
  {
    name: 'iPhone 14',
    url: 'https://i.ibb.co/5vc7J6s/iphone-14.png',
    category: 'smartphones',
    price: 999.99,
  },
];

// Get DOM elements
const productsWrapper = document.getElementById('products-wrapper');
const checkboxes = document.querySelectorAll('.check');
const filtersContainer = document.getElementById('filters-container');
const searchInput = document.getElementById('search');
const cartButton = document.getElementById('cart-button');
const cartCount = document.getElementById('cart-count');

// Initialize cart item count
let cartItemCount = 0;

// Initialize products
const productElements = [];

// Loop over the products and create the product elements
products.forEach((product) => {
  const productElement = createProductElement(product);
  productElements.push(productElement);
  productsWrapper.appendChild(productElement);
});

// Add filter event listeners
filtersContainer.addEventListener('change', filterProducts);
searchInput.addEventListener('input', filterProducts);

// Create product element
function createProductElement(product) {
  const productElement = document.createElement('div');

  productElement.className = 'item space-y-2';

  productElement.innerHTML = `
${product.name}

${product.name}

$${product.price.toLocaleString()}`; productElement .querySelector('.status') .addEventListener('click', updateCart); return productElement; } // Toggle add/remove from cart function updateCart(e) { const statusEl = e.target; if (statusEl.classList.contains('added')) { // Remove from cart statusEl.classList.remove('added'); statusEl.innerText = 'Add To Cart'; statusEl.classList.remove('bg-red-600'); statusEl.classList.add('bg-gray-800'); cartItemCount--; } else { // Add to cart statusEl.classList.add('added'); statusEl.innerText = 'Remove From Cart'; statusEl.classList.remove('bg-gray-800'); statusEl.classList.add('bg-red-600'); cartItemCount++; } // Update cart item count cartCount.innerText = cartItemCount.toString(); } // Filter products by search or checkbox function filterProducts() { // Get search term const searchTerm = searchInput.value.trim().toLowerCase(); // Get checked categories const checkedCategories = Array.from(checkboxes) .filter((check) => check.checked) .map((check) => check.id); // Loop over products and check for matches productElements.forEach((productElement, index) => { const product = products[index]; // Check to see if product matches the search or checked items const matchesSearchTerm = product.name.toLowerCase().includes(searchTerm); const isInCheckedCategory = checkedCategories.length === 0 || checkedCategories.includes(product.category); // Show or hide product based on matches if (matchesSearchTerm && isInCheckedCategory) { productElement.classList.remove('hidden'); } else { productElement.classList.add('hidden'); } }); }

Final Output:

Implementing Product Filtering with HTML, TailwindCSS, and JavaScript.gif

Conclusion:

Congratulations! You've successfully learned how to implement product filtering using HTML, TailwindCSS, and JavaScript. By following the steps outlined in this tutorial, you've gained valuable insights into creating dynamic and user-friendly filtering systems for your website.

Thank you for following along with this tutorial. We hope you found it informative and inspiring. Now go ahead and implement what you've learned to take your website to new heights of functionality and usability!

Code by: Brad Traversy

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post