The Code
async function getMovies() {
try {
let response = await fetch('https://api.themoviedb.org/3/movie/popular', {
headers: {
'Authorization': `Bearer ${API_KEY}`
}
});
let data = await response.json();
return data;
} catch (error) {
console.error(error);
}
}
async function displayMovies() {
const movieListDiv = document.getElementById('movie-list');
const moviePosterTemplate = document.getElementById('movie-card-template');
let data = await getMovies();
let movies = data.results; //movies is an array of objects
movies.forEach(movie => {
let movieCard = moviePosterTemplate.content.cloneNode(true);
let titleElement = movieCard.querySelector('.card-body > h5')
titleElement.textContent = movie.title;
let movieParagraphElement = movieCard.querySelector('.card-text');
movieParagraphElement.textContent = movie.overview;
let movieImgElement = movieCard.querySelector('.card-img-top');
movieImgElement.setAttribute('src', `https://image.tmdb.org/t/p/w500${movie.poster_path}`);
let infoButton = movieCard.querySelector('button.btn');
infoButton.setAttribute('data-movieId', movie.id);
movieListDiv.appendChild(movieCard);
});
}
async function getMovieDetails(movieId) {
try {
let response = await fetch(`https://api.themoviedb.org/3/movie/${movieId}`, {
headers: {
'Authorization': `Bearer ${API_KEY}`
}
});
let data = await response.json();
return data;
} catch (error) {
console.error(error);
}
}
async function showMovieDetails(btn) {
let movieId = btn.getAttribute('data-movieID');
let movie = await getMovieDetails(movieId);
let modal = document.getElementById('movie-modal');
let modalTitle = modal.querySelector('.modal-title');
modalTitle.textContent = movie.title;
let modalParagraph = document.getElementById('movie-modal-paragraph');
modalParagraph.textContent = movie.overview;
}
Code Explained:
This code is structured in four functions. The first function, getMovies is using an API
to retreive popular movie data. Then, the next function displayMovies is putting that
data onto my page. This second function is getting the data from the first and displaying the movie
poster, along with title and an overview of each movie on a card. The displayMovies
function runs when the page is loaded using onload in the body tag of the HTML.
Next, the getMovieDetails function is using the API to get more information about the
movies that will be displayed using a modal. I am getting each movie ID so that specific details
about each movie can be displayed on the page. Finally, the showMovieDetails function
is adding data from the movie ID to the modal so that each modal will display specific movie
information when clicked on. This can be customized to show other details such as genre, rating,
budget...etc.