Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Event listener not working after elements are rendered in the dom

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>

>Solution :

You could also just add the event on the div itself directly when you create it and pass the id or whatever you want.

<div class="category-card" id=${category.id} onclick="onCatClick(${category.id})">

After this, you can move your logic inside a top level onCatClick function.

function onCatClick(id) {
    console.log('Category clicked', id)
    window.location= 'movies.html?categoryId=' + id;
}

This is if your styling/layout doesn’t allow you to use an anchor element. Otherwise, you could simply replace the div with an anchor element:

<a href="movies.html?categoryId=${id}"></a>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading