Movies Listing

Project Description

Uses the Fetch API to retrieve a searchable list of movie titles and images from the Internet Movie Database.

Setting up the base web page

Your first task is to set up the base web page.

  1. In your portfolio/js folder, create a new sub-folder named movies.
  2. Download the following file to this new portfolio/js/movies folder.   index.html
  3. Give it the filename index.html.
  4. Update the website logo, favicon, <title> tag and the <footer> with your own details.

This file contains all the necessary HTML and CSS for this project.

Note: Ensure the file is linked to the lunadoge.min.css stylesheet, and not the older lunadoge.css version.

Adding the JavaScript code

At the bottom of your index.html web page, just before the closing </body> tag, add the following JavaScript code within a <script> tag.

const apiUrl = 'https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=04c35731a5ee918f014970082a0088b1&page=1';
const IMGPATH = "https://image.tmdb.org/t/p/w1280";
const SEARCHAPI =
   "https://api.themoviedb.org/3/search/movie?&api_key=04c35731a5ee918f014970082a0088b1&query=";

const main = document.getElementById("main");
const form = document.getElementById("form");
const search = document.getElementById("search");

showMovies(apiUrl);

function showMovies(url){
   fetch(url).then(res => res.json())
      .then(function(data){
         data.results.forEach(element => {
         const el = document.createElement('div');
         const image = document.createElement('img');
         const text = document.createElement('h2');
         text.innerHTML = truncateString(`${element.title}`, 20);
         image.src = IMGPATH + element.poster_path;
         el.appendChild(image);
         el.appendChild(text);
         main.appendChild(el);
      }); 
   });
}

form.addEventListener("submit", (e) => {
   e.preventDefault();
   main.innerHTML = '';
   const searchTerm = search.value;
   if (searchTerm) {
      showMovies(SEARCHAPI + searchTerm);
      search.value = "";
   }
});

function truncateString(str, num) {
   if (str.length >= num) {
      return str
   }
   return str.slice(0, num) + '...'
}

Save your file and verify it works correctly.

Upload the movies folder as a sub-folder of the portfolio/js folder on your GitHub account.