The reason for the error is due to the asynchronous nature of the code, where the button is not loaded yet. Is there a solution to this issue? It's difficult to explain in words but essentially, when the window is loaded, the button is not present as it only appears after clicking on an ID. I tried to include all the necessary codes but Stack Overflow requires a more detailed explanation.
Below is my main JavaScript code. The fetch function works correctly and I have omitted some of the codes for brevity.
const controlMovie = async() => {
const id = window.location.hash.replace('#', '');
if(id){
// new id
clearMovie();
state.control = new Control(id);
await state.control.getMovies();
UImovie(state.control);
}
return id;
};
const viewList = async() =>
{
const id = window.location.hash.replace('#', '');
state.view= new Control(id);
await state.view.getMovies();
UIlist(state.view);
}
['hashchange', 'load'].forEach(event => window.addEventListener(event, controlMovie));
document.querySelector('.add').addEventListener('click', viewList);
This part pertains to the UI JavaScript section
const UImovie = (info) => {
const markup = `
<div class="img-fig">
<img src="${info.image}" alt="${info.title}" class="movie-img">
</div>
<div class="movie_details">
<br>
<h3 style="align-items: center; font-weight: bold;"> ${info.title}</h3>
<p>Writer: ${info.writer}</p>
<p>Released date: ${info.year}</p>
<p>Actors: ${info.actors} </p>
<p>imdbRating: ${info.rating}</p>
<p>Total seasons: ${info.seasons}</p>
<p style="font-style: italic; color: red; font-size: 16px;"> "${info.story}"</p>
<button class= "add">+ Add to watchlist</button>
</div>
</div>
`;
document.querySelector('.movies-result').insertAdjacentHTML('afterbegin', markup);
};
const UIlist = (UI) => {
const markup = `
<h3> ${UI.title} <button class="icons"><ion-icon name="trash"></ion-icon></button></h3>
`;
document.querySelector('.lists').insertAdjacentHTML('afterbegin', markup);
}