Project Description
Uses the Fetch API to retrieve a searchable list of movie titles and images from the Internet Movie Database.
You can view a completed version of the project here.
Your project folder
In your portfolio/js folder is a folder named movies that contains all the files you need for this JavaScript project.
In VS Code, open the project’s index.html web page and ensure the hyperlinks and personal details have been correctly updated.
Adding the JavaScript code
Follow the steps below to add the JavaScript code to the index.html file.
- Scroll down the web page until you see an empty pair of opening <script> and closing </script> tags.
- Click inside the empty pair of tags and paste the JavaScript code below.
// Define the URL for fetching popular movies from the MovieDB API. const apiUrl = 'https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=04c35731a5ee918f014970082a0088b1&page=1'; // Base path for movie poster images from The Movie Database. const IMGPATH = "https://image.tmdb.org/t/p/w1280"; // Define the URL for searching movies by a query string. const SEARCHAPI = "https://api.themoviedb.org/3/search/movie?&api_key=04c35731a5ee918f014970082a0088b1&query="; // Get references to the main container and the form in the document. const main = document.getElementById("main"); const form = document.getElementById("form"); const search = document.getElementById("search"); // Call showMovies function initially with the popular movies URL. showMovies(apiUrl); // Asynchronous function to fetch movies and display them on the page. async function showMovies(url) { try { // Fetch the movie data from the API URL. const res = await fetch(url); // Convert the response to JSON. const data = await res.json(); // For each movie in the results, create and append elements to display it. data.results.forEach(element => { const el = document.createElement('div'); // Container for each movie. const image = document.createElement('img'); // To display the movie poster. const text = document.createElement('h2'); // To display the movie title. // If the title is too long, truncate it. text.innerHTML = truncateString(`${element.title}`, 20); // Set the source of the image to the full path including the base IMGPATH. image.src = IMGPATH + element.poster_path; // Append the image and text to the movie container. el.appendChild(image); el.appendChild(text); // Finally, append the movie container to the main content area. main.appendChild(el); }); } catch (error) { // If an error occurs during fetch or processing, log it to the console. console.log('Error fetching movies:', error); } } // Add an event listener to the form to handle movie searches. form.addEventListener("submit", (e) => { e.preventDefault(); // Prevent the form from submitting in the traditional way. main.innerHTML = ''; // Clear the main content area before displaying new results. const searchTerm = search.value; // Get the search term from the input field. if (searchTerm) { showMovies(SEARCHAPI + searchTerm); // Fetch and display movies based on the search term. search.value = ""; // Clear the search input field. } }); // Utility function to truncate a string to a specified length. function truncateString(str, num) { if (str.length > num) { return str.slice(0, num) + '...'; // Truncate and add ellipsis. } return str; // Return the original string if it's shorter than the specified length. }
- Save your index.html file.
- Display the file in a web browser and verify it works correctly.
Uploading your project to GitHub
Upload the movies folder as a sub-folder of the portfolio/js folder on your GitHub account.