Build a simple searchbar

Build a simple searchbar

Build a basic searchbar with Vanilla JS

A searchbar can be a very useful and powerful tool that you can use in a website. Depending on the application, it can be used to search a simple list or be used in very complex e-commerce websites. There are many powerful tools that can be used to search for a query today. But let's have a look at how to do it in a very basic application. So here I will show you how to build a simple searchbar that searches for a query from a list of characters with HTML,CSS and Javascript.

HTML

<div class="search-container">
    <input type="text" name="" id="search" placeholder="Search...">
</div>
<div id="container" class="card-container"></div>

I've defined the searchbar using the <input /> tag. It will display all the characters that match the query provided by user. Then we need to define a container where all the results will be displayed. I'll be building the content using JavaScript and let's see how.

CSS

.card-container {
  margin:1em 0;
  display:flex;
  max-width: 100%;
  flex-wrap:wrap;
  justify-content:center;
}

.character {
  margin : 1em;
  background-color:#bdefbd;
  border-radius:10px;
  padding: 1em;  
}

.search-container {
  display:flex;
  justify-content:center;
}

#search { 
  padding: 1em;
  border-radius:10px;
  border:2px solid #4169e1;
  font-size:16px; 
  width:100%;
}

The characters will be displayed as cards. So I've added basic CSS styles for the cards and the searchbar.

Javascript

let search = document.getElementById("search");
let container = document.getElementById("container");  
let characters = [] 

const getAllCharacters = async () => {
  const res = await fetch("https://rickandmortyapi.com/api/character")
  characters = await res.json()
  displayAll(characters.results) 
}

search.addEventListener("input",function(e) { 
  let query = e.target.value.toLowerCase(); 
  let filterCharacters = characters.results.filter(character => { 
    return character.name.toLowerCase().trim().includes(query)
  })  
  displayAll(filterCharacters)
})

function displayAll(characters) {   
    let html = characters.map(item => {
    return `<div class="character"> 
      <img src=${item.image} />
      <p class="name"><strong>Name: </strong>${item.name}</p>
      <p><strong>Gender:</strong> ${item.gender}</p>
      <p><strong>Origin:</strong> ${item.origin.name}</p>
      <p><strong>Species:</strong> ${item.species}</p>
    </div>
        `
  }).join('');
  container.innerHTML = html;
}

getAllCharacters();

This is the crucial part of this application. I have used the rickandmorty api to fetch data and display them as cards.

  • I call the api and pass the results to the displayAll function which displays all the characters.

For the searchbar, you need to filter the characters every time the user make an entry in the input.

  • I use an event listener on the <input /> tag. The event is input which is triggered whenever there's a change in input in the searchbar.

Notice I used the input event and not the change event.
The input event is triggered whenever there's a change in the text content of the input tag.
The 'change' event is triggered when the input loses focus from itself.

  • To display the filtered characters based on the user's input, I use the filter function filters the characters array and displays the filtered characters.

Summary

We learnt how to -

  • Trigger a bunch of tasks based on the user's input.
  • Fetch data from an api and displayed it using innerHTML.
  • Filter characters from the original set of characters and display them on the screen.

Here's an interesting article that I found regarding the onchange and oninput handlers that you might find useful.
If you are familiar with React, you should check this out.
The onchange handler in React doesn't behave the way the onchange handler behaves in vanilla JS? Know all about it here

I hope you found this helpful and an easy way to get started. Here's the working demo.