Every developer needs to know how to create a search bar because is used in almost every single site.
In this article, we are going to create search bar. We shall learn how to use the fetch
method. We shall make use of https://jsonplaceholder.typicode.com/users API.
How to setup
Create 3 files that are index.html
, styles.css
and script.js
- In the
index.html
file set up like this
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="styles.css">
<script src="script.js" defer></script>
<title>Javascript search bar</title>
</head>
<body>
<div class="search-wrapper">
<label for="search" >Search User</label>
<input type="search" id="search" data-search="">
</div>
<div class="user-cards" data-user-cards-container >
<template data-user-template>
<div class="card">
<div class="header" data-header></div>
<div class="body" data-body></div>
</div>
</template>
</div>
</body>
</html>
- In the
styles.css
style your input and the search results.
.search-wrapper{
display: flex;
flex-direction: column;
gap: .25rem;
}
input{
font-size: 1rem;
padding: .5rem;
}
.user-cards{
display: grid;
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
gap: .25rem;
margin-top: 1rem;
}
.card{
border: 1px solid black;
background-color: white;
padding: .5rem;
}
.card .header{
margin-bottom: .25rem;
}
.card > .body{
font-size: .8rem;
color: #777;
}
.hide {
display: none;
}
You've just prepared the static parts, lets get into the functionality part.
Whenever one types a username or email address, Javascript will only return the user and details that matches the input values. If no value matches then will return no results.
- In the
script.js
file Let's declare variables that will help us query the html.
const userCardTemplate = document.querySelector("[data-user-template]")
const userCardContainer = document.querySelector("[data-user-cards-container]")
const searchInput = document.querySelector("[data-search]")
Let's declare a variable that hold the users
const users = []
Let's fetch our users details from the API using our fetch method. In this point we are only concerned with the username and email address.
fetch("https://jsonplaceholder.typicode.com/users").then((res) => res.json()).then(data => {
users = data.map(user=> {
const card = userCardTemplate.content.cloneNode(true).children[0]
const header = card.querySelector("[data-header]")
const body = card.querySelector("[data-body]")
// adding content into the query selected i.e header and body
header.textContent = user.name
body.textContent = user.email
userCardContainer.append(card)
// return the result after successfull fetch
return {name: user.name, email: user.email, element: card}
});
})
We have successfully fetched our data from the API and rendered the results to the browser that should look like this.
Whenever a user types any letter, the field that matches the input will be displayed and the fields that does not contain such character is hidden.
Here is the code.
searchInput.addEventListener('input', (e) => {
const value = e.target.value
users.forEach((user) => {
const isVisible = user.name.toLowerCase().includes(value) || user.email.toLowerCase().includes(value)
user.element.classList.toggle('hide', !isVisible)
})
})
Here is the complete script.js
file
const userCardTemplate = document.querySelector("[data-user-template]")
const userCardContainer = document.querySelector("[data-user-cards-container]")
const searchInput = document.querySelector("[data-search]")
let users = []
fetch("https://jsonplaceholder.typicode.com/users").then((res) => res.json()).then(data => {
users = data.map(user=> {
const card = userCardTemplate.content.cloneNode(true).children[0]
const header = card.querySelector("[data-header]")
const body = card.querySelector("[data-body]")
// adding content into the query selected i.e header and body
header.textContent = user.name
body.textContent = user.email
userCardContainer.append(card)
// return the result after successfull fetch
return {name: user.name, email: user.email, element: card}
});
})
searchInput.addEventListener('input', (e) => {
const value = e.target.value
users.forEach((user) => {
const isVisible = user.name.toLowerCase().includes(value) || user.email.toLowerCase().includes(value)
user.element.classList.toggle('hide', !isVisible)
})
})
Recap
The search bar is an important feature in any software. But building it might be a challenge depending on the services you are using, eg using firebase firestore is a good example that may require you to use other services like Algolia and cloud functions
Am working on creating an article about firestore and Algolia search using cloud functions.
This article was originally published at melbite.com/building-the-search-bar-with-javascript-🧐
Top comments (0)