Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

156
Vistas
How to add event listener on <li> that are cloned on scroll

I have this scrolling div where if you scroll, it will clone the li tags and put them and the end so you have an infinite scroll. Here's the code for that:

infinite() {
  // it's a div, that holds your news
  // it holds ul with news in li elements
  const div = document.getElementById("container");
  div.addEventListener("scroll", function () {
    const maxScroll = this.scrollHeight - this.clientHeight;
    const currentScroll = this.scrollTop;
    const bottom = 100;
    if (currentScroll + bottom >= maxScroll) {
      const ul = document.getElementsByTagName("ul")[0];
      const current = parseInt(ul.dataset.current, 10);
      const li = document.querySelectorAll("li")[current];
      const newLi = li.cloneNode(true);
      ul.appendChild(newLi);
      ul.dataset.current = current + 1;
      console.log(li);
    }
  });
},

This works perfect for me. However, after the node is created, I can't put the event listener on the latest cloned li's because they are not in the DOM. How do I force the JS to put the event listener on newly cloned nodes? Here's the function for that:

 hover() {
  const rows = document.getElementsByClassName("plugin");
  rows.forEach((row) => {
    row.addEventListener("mouseover", () => {
      row.style.opacity = 1;
    });

    row.addEventListener("mouseout", () => {
      row.style.opacity = 0.3;
    });
  });
},
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Just delegate

const ul = document.querySelector("#container ul");

ul.addEventListener("mouseover", e => {
  const tgt = e.target;
  if (tgt.tagName === "LI") tgt.style.opacity = 1;
})
ul.addEventListener("mouseout", e => {
  const tgt = e.target;
  if (tgt.tagName === "LI") tgt.style.opacity = .3;
});

or simply use CSS

#container li { opacity: .3 }    
#container li:hover { opacity: 1 }
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda