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:
Knowledge of HTML, CSS, and Javascript. This article is neither an introduction to HTML, CSS, or Javascript.
Knowledge of Application Programming Interface (API)
An account with The Movie Database (TMDB).
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>
- 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" />
- The
link
tag in thehead
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>
The
<form>
element is used to create a container for theinput
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>
- The
div
with a class ofsearch-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;
}
The
.form
class set the width container to70%
of its parent element and themargin
element is set to25px
for the top and bottom. Andauto
margin on the left and right which centers the form element horizontally.The
input
field has a width of80%
of its parent element, aheight
of28px,
and a font size of1.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')
- Each of the elements is given a variable using the
const
type. These variables are used to reference elements in the HTML document using thedocument.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}`;
}
- A function called
searchMovies
is defined using theasync
keyword to indicate that takes aquery
parameter and uses it to construct an API URL that queries the themoviedb.org API for movie results.
try {
const response = await fetch(apiUrl);
const data = await response.json();
const movies = data.results;
- The
try
block of the function executes an asynchronousfetch
request to retrieve data from the API URL. The response is then parsed into JSON format using thejson()
method, and saved into adata
variable.
searchResults.innerHTML = '';
- The
innerHTML
of the movie result is set to an empty variable. This means that whenever you make a new a new search is made, 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);
});
}
The function uses
forEach
loop to iterate through each movie object in the array, and extracts several properties from each movie, including the poster imageURL
,title
,release date
, andvote average
.It also creates a new
div
element to represent each movie and sets theinnerHTML
of the element to a string of HTML code that includes animg
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 thesearchResults
container.
catch (error) {
console.error(error);
}
}
- 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);
});
- 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);
});
- 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 thequery
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 contents on web development.