Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

167
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda