I am trying to fetch information from TheMovieDB.org using API, I made a simple code to do that, but it works when I add click event to a button/hyperlink, then it displays all the NowPlayingMovies. I want the webpage should display now playing movies itself without any need to click on a button.
I tried to use the window.onload
function and put the whole code in one function and remove the need to click on the hyperlink but I am unable to do it and code does not work and shows various errors. Can someone please help me fix it?
window.onload = function updateLatestMovies() {
const xhr = new XMLHttpRequest();
const nowPlayingButton = document.querySelector("#nowPlayingButton");
const endPoint = `https://api.themoviedb.org/3/movie/now_playing?api_key=6a879a78d6083b8f3ba308233e0de85b&language=en-US&page=1`;
xhr.open("GET", endPoint);
xhr.send();
xhr.addEventListener("readystatechange", updateLatestMovies);
const nowPlaying = document.querySelector("#nowPlaying");
if (xhr.readyState == 4) {
const response = JSON.parse(xhr.responseText);
const nowPlayingOutput = document.querySelector("#nowPlaying");
let nowPlayingA = response.results;
let output = "";
for (let i = 0; i < 15; i++) {
output += `
<div id="card">
<a onclick="movieSelected('${nowPlayingA[i].id}')" href="#"><img src="http://image.tmdb.org/t/p/w400/${nowPlayingA[i].poster_path}"></a>
<div class="cardContent">
<a onclick="movieSelected('${nowPlayingA[i].id}')" href="#"><h2>${nowPlayingA[i].title}</h2></a>
<p id="p_rating"><strong>Rating:</strong> <span>${nowPlayingA[i].vote_average} / 10 </span> </p>
<p><strong>Release date:</strong> <span>${nowPlayingA[i].release_date} </span></p>
</div>
</div>`;
}
nowPlayingOutput.innerHTML = output;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Movies Database</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<a href="#nowPlaying" id = "nowPlayingButton" class="btn">See what's on Cinema!</a>
<div id="nowPlaying">
</div>
</body>
</html>
And I got the following error:
Uncaught TypeError: Cannot read property 'addEventListener' of null at movie.js:4