I am creating a project that when I click a certain category card I get the id of that category and redirect to movies screen.
I am aware that the row.eventlistener() in index.js it will be executed before the elements are rendered and that is why it does not pick the id. How should I add the event listener to each newly rendered item before adding it to the container so that I can get the id for each category card.
index.js
async function getCategories() {
let url = 'http://localhost:8080/movieCategories';
try {
let res = await fetch(url);
return await res.json();
} catch (error) {
console.log(error);
}
}
async function renderCategories() {
let categories = await getCategories();
let html = '';
categories.forEach(category => {
let htmlSegment = `
<div class="category-card" id=${category.id}>
<img src="./assets/images/sci-fi.jpg" alt="" class="card-img">
<div class="name">${category.name}</div>
</div>
`;
html += htmlSegment;
});
let container = document.querySelector('.category-grid');
container.innerHTML = html;
}
renderCategories();
document.querySelectorAll('div.category-card').forEach(row=>{
row.addEventListener('click',event=>{
console.log('Category clicked', event.currentTarget.id)
window.location= 'movies.html?categoryId=' +event.currentTarget.id;
});
});
index.html
<section class="category" >
<h2 class="section-heading">Category</h2>
<div class="category-grid">
</div>
</section>