I am trying to create a complex project: a Youtube UI clone, and I had a problem with JS
the idea
the idea is: on scroll more divs should be created automatically, similar to the first one (and that's working fine)
the problem
but when I want to put an event listener for click, JavaScript does not handle the events on subsequent divs,
but in reality, there are automatically generated 50 ~ 100 other divs (with the same class)
so I think there is something wrong with .length
here the website for giving you a idea of the problem:
https://laaouatni.github.io/yt-clone/
here where I think the problem is:
function createVideo() {
let videoComponent = videoContainer.cloneNode(true);
mainContainer.appendChild(videoComponent);
}
...
<main>
<div class="video-container">
...
</div>
<!-- here javascript will put other divs on scroll -->
</main>
...
window.addEventListener("scroll", function() {
let scrollPercentage = (window.scrollY / (document.body.scrollHeight - window.innerHeight)) * 100;
if (scrollPercentage > 70) {
createVideo();
}
}
let videoContainer = document.querySelector(".video-container");
let allVideoContainer = document.querySelectorAll(".video-container");
for (let index = 0; index < allVideoContainer.length; index++) {
allVideoContainer[index].addEventListener("click", function() {
console.log("clicked video N " + index);
})
}
if I click the div that was written manually, it executes the click function, but with the generated divs the click does not work. I don't know if the DOM doesn't update or should I write something more? on the internet there is no result for solving the problem (I hope to find someone with experience, who can help me here)