Open In App

Movie Search Application using JavaScript

Last Updated : 01 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to make a movie search application using JavaScript. It will use an API which is a RESTful web service to obtain movie information. We will be using HTML to structure our project, CSS for designing purposes and JavaScript will be used to provide the required functionality.

Preview Image:

Screenshot-2023-11-29-111527

Prerequisites:

Approach:

  • Start by creating the HTML structure for your Movie Search Application. Use semantic tags like <header>, <main>. Include Input tag and a search button.
  • Style your website using CSS to enhance its visual appeal and responsiveness.
  • Use JavaScript to add interactivity to your movie search app. Utilize document.getElementById to select HTML elements like buttons and the container for displaying movie results. Implement event listeners for interactive elements such as the search button.
  • Implement the logic to fetch movie data from an API (e.g., OMDB API) and display the results dynamically on the webpage.
  • Adding proper validations, such as checking if the search input is empty, handling errors during API fetch.

OMDb API:

  • OMDb API which is a RESTful web service to obtain movie information.
  • To get your api key visit: OMDb api key

Example: In this example we have used above explained approach.

HTML




<!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="style.css">
    <title>Movie Search App</title>
</head>
  
<body>
    <header>
        <h1>Search Your Movies Here!</h1>
    </header>
    <main>
        <input type="text" id="searchInput"
        placeholder="Search for a movie..."
        autocomplete="off">
        <button onclick="searchMovies()">Search</button>
        <div id="MoviesGrid">
  
        </div>
    </main>
    <script src="index.js"></script>
</body>
  
</html>


CSS




/* Write CSS Here */
body {
    font-family: 'Arial', sans-serif;
    background-color: #f4f4f4;
    margin: 0;
    padding: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
}
  
header {
    background-color: #00a310;
    width: 100%;
    color: #fff;
    padding: 1rem;
    text-align: center;
}
  
main {
    margin: 2rem;
    text-align: center;
}
  
input {
    padding: 0.5rem;
    font-size: 1rem;
    border-radius: 20px;
}
  
button {
    padding: 0.5rem 1rem;
    font-size: 1rem;
    cursor: pointer;
}
  
#MoviesGrid {
    margin-top: 2rem;
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
}
  
.movie-card {
    width: calc(25% - 20px);
    /* 25% width with margin */
    margin: 10px;
    /* Increased margin */
    text-align: center;
}
  
.movie-card img {
    max-width: 100%;
    /* Ensure image is responsive */
    height: auto;
    /* Maintain aspect ratio */
}
  
@media screen and (max-width: 1200px) {
    .movie-card {
        width: calc(33.33% - 20px);
    }
}
  
@media screen and (max-width: 800px) {
    .movie-card {
        width: calc(50% - 20px);
    }
}
  
@media screen and (max-width: 600px) {
    .movie-card {
        width: calc(100% - 20px);
    }
}


Javascript




document.addEventListener('DOMContentLoaded', function () {
    fetchmovies();
});
  
function fetchmovies() {
    // omdb API key
    const apiKey = 'YOUR_OMDB_API_KEY';
  
    // MoviesGrid element
    const MoviesGrid = document.
        getElementById('MoviesGrid');
  
    // Display loading message
    MoviesGrid.innerHTML =
        '<p>Loading movies...</p>';
  
    const randomSearchTerms =
        ['action', 'comedy', 'drama', 'adventure'];
    const randomTerm = randomSearchTerms[
        Math.floor(Math.random() *
            randomSearchTerms.length)];
  
    // Fetch movie data from OMDB API with 
    // a default search term (e.g., 'popular')
    fetch(`http://www.omdbapi.com/?apikey=
          ${apiKey}&s=${randomTerm}`)
        .then(response => response.json())
        .then(data => {
            if (data.Search && data.Search.length > 0) {
                moviestoshow(data.Search);
            } else {
                MoviesGrid.innerHTML =
                    '<p>No random movies found!</p>';
            }
        })
        .catch(error => {
            console.error('Error fetching random movies:', error);
            MoviesGrid.innerHTML =
          '<p>Error fetching movies. Please try again later.</p>';
        });
}
  
function searchMovies() {
    // omdb API key
    const apiKey = 'YOUR_API_KEY';
    const searchInput = document.
        getElementById('searchInput').value;
  
    // MoviesGrid element
    const MoviesGrid = document.
        getElementById('MoviesGrid');
  
    // Search result validation
    if (searchInput.trim() !== '') {
  
        // Display loading message
        MoviesGrid.innerHTML = '<p>Loading movies...</p>';
  
        // Fetch movie data from OMDB API
        fetch(`http://www.omdbapi.com/?apikey=
             ${apiKey}&s=${searchInput}`)
            .then(response => response.json())
            .then(data => {
                if (data.Search && data.Search.length > 0) {
                    moviestoshow(data.Search);
                } else {
                    MoviesGrid.innerHTML =
             '<p>No movies found with the given name!</p>';
                }
            })
            .catch(error => {
                console.error('Error fetching data:', error);
                MoviesGrid.innerHTML =
           '<p>Error fetching movies. Please try again later.</p>';
            });
    } else {
        alert('Enter a movie title then search!');
    }
}
  
function moviestoshow(movies) {
    const MoviesGrid = document.
        getElementById('MoviesGrid');
  
    // Clear previous results
    MoviesGrid.innerHTML = '';
  
    // Display each movie in the results
    movies.forEach(movie => {
        const movieCard = document.createElement('div');
        movieCard.classList.add('movie-card');
  
        movieCard.innerHTML = `
      <img src="${movie.Poster}" alt="${movie.Title}">
      <h2>${movie.Title}</h2>
      <p>${movie.Year}</p>
    `;
  
        MoviesGrid.appendChild(movieCard);
    });
}


Output:

moviesearch1



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads