Create a Search Filter with HTML, CSS, and JavaScript (Source Code)


By Faraz -

Learn how to create a responsive search filter using HTML, CSS, and JavaScript. Improve user experience and boost website usability.

Create a Search Filter with HTML, CSS, and JavaScript (Source Code).jpg

Table of Contents

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

Welcome to a comprehensive tutorial on creating a dynamic and interactive search filter using the combined power of HTML, CSS, and JavaScript. In this digital age, user experience is paramount, and a well-designed search filter can be the key to unlocking seamless navigation and content discovery on your website.

Imagine a scenario: a visitor lands on your website in search of specific information or products. Without a search filter, they might find themselves scrolling endlessly through pages or sifting through an overwhelming amount of content. This is where our tutorial comes in handy. By the end of this guide, you'll be equipped with the skills to craft a sophisticated search filter that empowers users to precisely refine their search criteria, leading them to the content they desire in a matter of seconds.

But why is a search filter so important? It's simple – humans have an insatiable need for efficiency. We want information at our fingertips, and we want it fast. A well-implemented search filter not only satisfies this need but also enhances user satisfaction and boosts the credibility of your website. Visitors are more likely to stay and explore when they can effortlessly find what they're seeking.

In the sections that follow, we'll embark on a step-by-step journey through the creation of this search filter. We'll start with the basics, ensuring everyone, regardless of their development expertise, can follow along. As we progress, we'll delve into the intricacies of HTML, CSS, and JavaScript, gradually crafting a fully functional and visually appealing search filter.

No matter if you're a seasoned developer aiming to amplify your skill set or a beginner taking your first steps into the world of web development, this guide is tailored to your needs. We encourage you to dive in with curiosity, experiment, and embrace the creative process. By the time you reach a conclusion, you'll have a search filter that not only serves a practical purpose but also exemplifies your dedication to a user-centric web experience.

So, let's roll up our sleeves and embark on this rewarding journey of creating a dynamic search filter – where technology meets user intuition and your website transforms into an oasis of streamlined content discovery.

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our search bar.

After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

Let's break down each part of the code:

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

2. <html lang="en">: The opening <html> tag defines the start of an HTML document. The lang attribute indicates that the document is in English.

3. <head>: The <head> section contains metadata and links to external resources used by the page.

  • <title>: Sets the title of the web page, which is displayed in the browser's title bar or tab.
  • <meta charset="UTF-8">: Specifies the character encoding for the document (UTF-8 in this case, which supports a wide range of characters).
  • <meta name="viewport" content="width=device-width">: Defines the viewport settings for responsive design on various devices.
  • <link href="" rel="stylesheet">: Links to an external stylesheet that provides Font Awesome icons.
  • <link rel="stylesheet" href="styles.css">: Links to an external stylesheet named "styles.css" for additional styling.

4. <body>: The main content of the webpage is contained within the <body> tag.

  • .search-container.main-container: A <div> element with class names "search-container" and "main-container." It holds the search input field and icon.
  • <i class="fa fa-search"></i>: An Font Awesome icon for the search functionality.
  • <input type="text" id="search-input" placeholder="Search..." autocomplete="off">: An input field for searching. It has an ID of "search-input," a placeholder text, and autocomplete turned off.
  • .main-container: Another <div> element with the class "main-container" that holds the content of the page.
  • <div id="nothing-alert">Nothing Found</div>: A div with the ID "nothing-alert" that displays a message when no search results are found.
  • .cards: A series of <div> elements with the class "cards" that represent different car brands.
  • <h2 class="icon-name">Brand Name</h2>: Heading level 2 containing the name of a car brand, and a class "icon-name" for styling.

5. <script src="script.js"></script>: A reference to an external JavaScript file named "script.js" that contains the logic for the search filter functionality.

This is the basic structure of our search bar using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the search bar is in place, the next step is to add styling to the search filter using CSS.

Next, we will create our CSS file. In this file, we will use some basic CSS rules to create our search filter.

Let's break down each part of the code:

1. @import Rule: This imports an external stylesheet from Google Fonts, specifically the "Poppins" font with various weights (400, 500, 600, 700) and the "swap" display mode. This makes the "Poppins" font available for use throughout the webpage.

2. *: This selector targets all elements on the page and sets their box-sizing to border-box. This ensures that padding and border are included in the element's total width and height.

3. body: Styles applied to the <body> element:

  • Sets the font-family to "Poppins" or a generic sans-serif font if "Poppins" is not available.
  • Sets the text color to black.
  • Sets the background color to a light grayish color (#ccccd2).
  • Uses flexbox properties to center content vertically and horizontally.
  • Sets a fixed width of 500px and centers the container horizontally using auto margin.

4. .main-container: This class styles a container for the main content:

  • Uses flexbox to align items in a row, starting from the left.
  • Adds margin around the container.
  • Allows flex items to wrap to a new line if they exceed the container's width.

5. #nothing-alert: Styles for an element with the ID "nothing-alert" (which might be used to display a message or alert):

  • Sets the display to none, initially hiding the element.
  • Sets width to 100% and centers it horizontally using auto margin.
  • Centers text within the element.

6. .cards: Styles for elements with the class "cards" (possibly used for displaying cards or buttons):

  • Uses flexbox to center content both vertically and horizontally.
  • Sets a fixed width and height for the element.
  • Adds margin around the element.
  • Applies a white background, border radius, and box shadow to create a card-like appearance.
  • Adds a subtle hover effect with a scale transformation and increased box shadow.

7. @keyframes populate: Defines a keyframe animation named "populate":

  • The animation starts with a transform scale of 0 (shrinking the element).
  • This animation is intended to be used to grow the element from a hidden state.

8. .icon-name: Styles for elements with the class "icon-name":

  • Sets the font size to 0.7em.
  • Centers text horizontally.
  • Removes margin.

9. .search-container: Styles for a container, possibly used for a search input:

  • Uses relative positioning.
  • Sets a fixed height and maximum width for the container.
  • Applies a white background, border radius, and box shadow.

10. .search-container i: Styles for <i> elements (likely used for icons) within the search container:

  • Uses absolute positioning.
  • Sets the position to the left of the container.
  • Sets the font size and color of the icon.

11. #search-input: Styles for an element with the ID "search-input" (probably a search input field):

  • Sets the height and width to 100%.
  • Removes outline.
  • Sets font size, weight, and padding.
  • Sets a transparent background.

12. @media query: This query applies styles when the screen width is 786px or smaller:

  • Adjusts the width of .search-container to 50% to better fit smaller screens.

This will give our search filter an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

@import url(';500;600;700&display=swap');

* {
  box-sizing: border-box;

body {
  font-family: 'Poppins', sans-serif;
  color: black;
  background-color: #ccccd2;
  display: flex;
  justify-content: center;
  flex-direction: column;
  width: 500px;
  margin: 0px auto;

.main-container {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin: 15px 40px;
  flex-wrap: wrap;

	display: none;
	width: 100%;
	margin: 50px auto;
  text-align: center;

.cards {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  width: 80px;
  height: 80px;
  margin: 0.5em;
  background-color: #fff;
  border-radius: 3px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.25s ease;
  animation: populate 0.5s ease-out normal backwards;

.cards:hover {
  transform: scale(1.05);
  z-index: 1;
  box-shadow: 0 5px 12px rgba(0, 0, 0, 0.2);

@keyframes populate {
  0% {
    transform: scale(0);

.icon-name {
  font-size: 0.7em;
  text-align: center;
  margin: 0;

  position: relative;
  height: 45px;
  max-width: 650px;
  width: 70%;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1); 

.search-container i {
  position: absolute;
  left: 20px;
  font-size: 16px;
  color: #707070;

  height: 100%;
  width: 100%;
  outline: none;
  font-size: 16px;
  font-weight: 400;
  border: none;
  padding-left: 50px;
  background-color: transparent;

@media screen and (max-width: 786px) {
    width: 50%;

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript to filter and display cards based on the user's search input.

Let's break down the code step by step:

1. The code begins by adding an event listener to the DOMContentLoaded event. This event fires when the initial HTML document has been completely loaded and parsed. When this event occurs, the provided function will be executed.

2. Inside the event listener function, the code retrieves references to two important elements in the webpage:

  • searchInput: This is a reference to an input field with the id "search-input". It represents the text input where the user can enter their search query.
  • cards: This is a collection of elements with the class "cards". These elements likely represent the cards that need to be filtered based on the search query.

3. The filterIcons function is defined to perform the filtering of cards based on the provided search query. The function takes one parameter, searchQuery, which represents the user's input text.

4. The code retrieves a reference to an element with the id "nothing-alert". This element is likely an alert or message that will be displayed if no matching cards are found.

5. The number variable is initialized to keep track of the number of matching cards found.

6. The code uses the forEach method to iterate over each card element in the cards collection. For each card, it retrieves the text content of the <h2> element (likely a title) and converts it to lowercase. It then checks if the searchQuery (also converted to lowercase) is included in the name (title) of the card.

  • If the search query is found in the card's title, the nothingfound alert is hidden (style.display set to "none"), and the card is displayed by setting its style.display to "flex". The number variable is incremented to keep track of the number of matches.
  • If the search query is not found in the card's title, the card is hidden (style.display set to "none").

7. After iterating through all the cards, the code checks if the number is still 0. If no matches are found, it displays the "nothing-alert" by setting its style.display to "block".

8. An event listener is added to the searchInput element for the "input" event. This event fires when the user types or makes an input in the search field.

9. Inside the event listener for the "input" event, the code retrieves the trimmed value of the search input (removing leading and trailing whitespace) and then calls the filterIcons function with the trimmed search query.

Create a JavaScript file with the name of script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document, so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

document.addEventListener('DOMContentLoaded', function () {
  const searchInput = document.getElementById('search-input');
  const cards = document.querySelectorAll('.cards');

  function filterIcons(searchQuery) {
	  const nothingfound = document.getElementById("nothing-alert");
	  let number = 0;
		cards.forEach(function (card) {
      const name = card.querySelector("h2").textContent.toLowerCase();
      if (name.includes(searchQuery.toLowerCase())) { = "none"; = "flex";
      } else { = "none";
	if(number == 0){ = "block";

  searchInput.addEventListener("input", function () {
    const searchQuery = searchInput.value.trim();

Final Output:

Create a Search Filter with HTML, CSS, and JavaScript (Source Code).gif

See the Pen Test by Faraz (@codewithfaraz) on CodePen.


Congratulations! You've reached the end of our in-depth tutorial on creating a search filter using HTML, CSS, and JavaScript. You've embarked on a journey that has equipped you with the tools to enhance user experience and efficiency on your website.

By now, you've learned the art of structuring a search filter using HTML, styling it with CSS to seamlessly blend with your website's design, and infusing it with dynamic functionality through JavaScript. The synergy of these three technologies has empowered you to provide your visitors with an intuitive and powerful search tool.

As you reflect on your accomplishments, consider the impact of your newfound knowledge. Your website is now equipped with a feature that not only saves your users' time but also sets a standard for user-centric design. With a well-implemented search filter, you've transformed your website into a hub of accessible and organized content, leaving a positive and lasting impression on your visitors.

But remember, this journey is just the beginning. Web development is an ever-evolving field, and as you continue to explore and refine your skills, you'll find endless opportunities to further enhance your website's functionality and user experience. Embrace the spirit of innovation, stay curious, and always keep the user at the center of your design decisions.

We hope this tutorial has been both enlightening and inspiring. Whether you're a hobbyist, a professional developer, or anyone in between, creating a search filter is a valuable addition to your skill set. Now it's time to take what you've learned, experiment, and adapt it to your unique projects.

Thank you for joining us on this journey. Your commitment to improving web experiences is a testament to the ever-evolving landscape of the digital world. Here's to many more successful and user-friendly web projects in your future. Happy coding!

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!

Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox

Latest Post