DEV Community

Cover image for Building Live Search Functionality with JavaScript
Tracy | Software Engineer
Tracy | Software Engineer

Posted on

Building Live Search Functionality with JavaScript

Introduction

The live search function is an important tool in modern websites that filters results based on a user's preference. This improves customers' experience and saves users the stress of navigating through hundreds of results to find a specific item.

A live search bar is an important tool for enhancing user experience, boosting engagement, and giving website administrators useful insights. It can increase traffic, boost conversion rates, and ultimately result in more success for a website or application by making it simpler for people to locate what they're looking for.

Project Overview

In this article, you will build a search bar that gives you the result for movies when you search for a particular movie. You will build this project with the use of HTML, CSS, and JavaScript.

Prerequisites

The prerequisites for following along with this project include the following:

HTML - Create the UI

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
  <title>Searchbar</title>
</head>
<body>
  <form action="/" class="search-btn">
    <i class="fa fa-search searchIcon" aria-hidden="true"></i>
    <input type="text" placeholder="search for a movie...">
  </form>

  <div class="search-results"></div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
  • The above line of code above contains an HTML boilerplate with HTML code that creates a search form with a text input field for entering movie titles, and a container for displaying the search results.
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
Enter fullscreen mode Exit fullscreen mode
  • The link tag in the head content is a font icon link that will display a search bar icon.
<form action="/" class="search-btn">
    <i class="searchIcon" aria-hidden="true"></i>
    <input type="text" placeholder="search for a movie...">
</form>
Enter fullscreen mode Exit fullscreen mode
  • The <form> element is used to create a container for the input field with an action of /, which means it will submit to the current page.

  • The <i class="searchIcon" aria-hidden="true"></i> is a search bar icon tag from font-awesome which will display movie results when clicked.

  • The input field is where users will enter search queries. The placeholder attribute indicates the kind of input expected in the field.

<div class="search-results"></div>
Enter fullscreen mode Exit fullscreen mode
  • The div with a class of search-result is a container that will display the results.

CSS - Style the UI

.form{
  width: 70%;
  margin: 25px auto;
}

input{
  width: 80%;
  height: 28px;
  font-size: 1.1rem;
  padding-left: 40px;
}

.searchIcon{
  position: relative;
  left: 30px;
}
Enter fullscreen mode Exit fullscreen mode
  • The .form class set the width container to 70% of its parent element and the margin element is set to 25px for the top and bottom. And auto margin on the left and right which centers the form element horizontally.
  • The input field has a width of 80% of its parent element, a height of 28px, and a font size of 1.1rem which is relative to the root font size.

JavaScript

const form = document.querySelector('.form');
const input = form.querySelector('input');
const searchResults = document.querySelector('.search-results');
const searchIcon = document.querySelector('.searchIcon')
Enter fullscreen mode Exit fullscreen mode
  • Each of the elements is given a variable using the const type. These variables are used to reference elements in the HTML document using the document.querySelector().
const searchMovies = async (query) => {
  const apiKey = 'apiKey'; // replace this part with your actual API key
  const apiUrl = `https://api.themoviedb.org/3/search/movie?api_key=${apiKey}&query=${query}`;
}
Enter fullscreen mode Exit fullscreen mode
  • A function called searchMovies is defined using the async keyword to indicate that takes a query parameter and uses it to construct an API URL that queries The movie database (TMDB) API for movie results.
try {
    const response = await fetch(apiUrl);
    const data = await response.json();
    const movies = data.results;
Enter fullscreen mode Exit fullscreen mode
  • The function try block executes an asynchronous fetch request to retrieve data from the API URL. The response is then parsed into JSON format using the json() method, and saved into a data variable.
searchResults.innerHTML = '';
Enter fullscreen mode Exit fullscreen mode
  • The innerHTML of the movie result is set to an empty variable. This means that whenever you make a new search, the page will research to show the new research result.
movies.forEach((movie) => {
      const { poster_path, title, release_date, vote_average } = movie;

      const movieContainer = document.createElement('div');
      movieContainer.classList.add('movie');

      const posterUrl = poster_path
        ? `https://image.tmdb.org/t/p/w500/${poster_path}`
        : 'https://via.placeholder.com/500x750?text=No+poster';

      movieContainer.innerHTML = `
        <img src="${posterUrl}" alt="${title}" />
        <div class="movie-info">
            <h3>${title}</h3>
            <small>Released on ${release_date}</small>
            <span class="rating">${vote_average}</span>
        </div>
      `;

      searchResults.appendChild(movieContainer);
    });
}
Enter fullscreen mode Exit fullscreen mode
  • The function uses forEach loop to iterate through each movie object in the array, and extracts several properties from each movie, including the poster image URL, title, release date, and vote average.
  • It also creates a new div element to represent each movie and sets the innerHTML of the element to a string of HTML code that includes an img for the movie poster, span for the rating, h3 for the movie title, and release date.
  • The function then appends the new movie div element to the searchResults container.
catch (error) {
    console.error(error);
  }
}
Enter fullscreen mode Exit fullscreen mode
  • The above code will log any errors that may occur during the API request or movie data processing.
form.addEventListener('submit', async (event) => {
  event.preventDefault();
  const query = input.value;
  searchMovies(query);
});
Enter fullscreen mode Exit fullscreen mode
  • The EventListener listens for a click event when the form is submitted and displays the result.
searchIcon.addEventListener('click', async () => {
  const query = input.value;
  searchMovies(query);
});
Enter fullscreen mode Exit fullscreen mode
  • An EventListener is added to the search bar icon so that when the icon is clicked, the event listener calls the searchMovies function, passing in the current value of the input field as the query parameter.

Conclusion

A functional search is implemented in almost modern websites to ease the stress of users who visit the website. Knowing how to implement one will improve one's skill as a developer.

I hope you found this article useful, please like, follow, and share with your friends. I post content on web development.

Top comments (0)