Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!