Building a Search Bar in JavaScript

Building a Search Bar in JavaScript

Introduction

In this article, you will learn how to build a Search Bar using HTML, CSS and JavaScript (JS) and also get a basic understanding of how DOM and fetch() work. Note, that this is not a beginner's tutorial on building a website. So you need to have a basic understanding of HTML, CSS and JS. By the end of this tutorial the website should look like this:

codepen_2022-7-17.gif

The Codes

For the sake of those that want to write the code without understanding it at first (of which I am one), the code will be shown first. You can copy the codes into your project folder to see it run in your browser, then you read the rest of the article to understand what you just copied. But if you really want to learn it well, a more prefered way will be to read the article while writing the functions one by one.

Create a project folder with any name of your choice. e.g. searchBar

  • Inside this folder create a file index.html;
<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="style.css">
    <title>searchBar</title>
</head>
<body>
    <section class="searchBar">
        <div class="search">
          <input type="search" id="search">
        </div>
        <div class="content" id ="box">
        </div>
      </section>
    <script src="/index.js"></script>
</body>
</html>
  • Then create another file style.css;
@import url('https://fonts.googleapis.com/css2?family=Space+Mono&display=swap');
*{
  margin:0px;
  padding:0px;
  box-sizing:border-box; 
  font-family: 'Space Mono', monospace;
  font-size:15px;

}
.searchBar{
  padding:25px;
  display:flex;
  gap:20px;
  flex-direction:column;
  justify-content:center;
  align-items:center;
}
.content{
  width:50%;
  display:grid;
  gap:10px;
  grid-template-columns: repeat(auto-fill,minmax(200px,1fr));
}
.card{
  box-shadow: 3px 2px 5px rgba(0,0,0,0.3);
  border-radius:5px;
  background-color:#eee;
  padding:20px
}
.card_email{
  font-size:12px;
  color:grey;
}
.hide{
  display:none;
}
input[type = search]{
  border-radius: 25px;
  padding: 0 10px;
  border: 1px solid grey;
  outline: none
}
  • And finally the script.js;
const URL = "https://jsonplaceholder.typicode.com/users";
const input = document.getElementById("search");
const content = document.getElementById("box");
let users = [];

input.addEventListener("input", (e) => {
  users.forEach((user) => {
    const isVis =user.name.toLowerCase().includes(e.target.value) || user.email.toLowerCase().includes(e.target.value);
    user.elem.classList.toggle("hide", !isVis);
  });
});

fetch(URL)
  .then((res) => res.json())
  .then((data) => {
    users = data.map(display);
  });

function display(obj) {
  const card = document.createElement("div");
  card.classList.add("card");
  const sec = `<h1 class="card__name">${obj.name}</h1><p class="card_email">${obj.email}</p>`;
  card.innerHTML = sec;
  content.append(card);
  return { name: obj.name, email: obj.email, elem: card };
}

How it works

First of all the data in real life, we will be getting the data from API. To mimic the IRL situation we will be using https://jsonplaceholder.typicode.com/users Which returns an array of 10 objects.

Let's fetch the data from API for this we will be using the fetch() method

fetch(URL)
  .then((res) => res.json())
  .then((data) => {
    users = data.map(display);
  });

After fetching the response convert it to JSON using the JSON() method. then we will map the data array with the display function and store data for later use.

Now, the Display function takes the object as an argument and loads Dom with necessary information. To display we create Div with the “.card” class for that we will use createElement(). To add class we used the classList method. To add Content we have a couple of options but due to simplicity we will be using template literals and innerHTML

Note:- it is not recommended to use innerHTML in production because its prone to cross-site scripting

function display(obj) {
  const card = document.createElement("div");
  card.classList.add("card");
  const sec = `<h1 class="card__name">${obj.name}</h1><p class="card_email">${obj.email}</p>`;
  card.innerHTML = sec;
  content.append(card);
  return { name: obj.name, email: obj.email, elem: card };
}

Now the last part We will add EventListener to the Input and Listen to the input event. For every event, we will traverse through using the forEach method and if the input value is present we will add a “.hide” class to that element.

input.addEventListener("input", (e) => {
  users.forEach((user) => {
    const isVis =user.name.toLowerCase().includes(e.target.value) || user.email.toLowerCase().includes(e.target.value);
    user.elem.classList.toggle("hide", !isVis);
  });
});

Conclusions

Building a simple Search bar in JavaScript is an excellent, simple and fun project for beginners to start with because it helps you understand an initially complex logic used in the simplest of ways. In the next article, we will be talking about debounce and throttle methods and implementing these functions.

HINT: debounce and throttle are ways to optimize search feature