So I am trying to create a grid of videos in which the "placeholder" picture is replaced by a video next to it in DOM on click.
The code I have written works well if there is one picture/video, but there should be 6. I have tried working through the array of placeholders (with for (let i...)), but then the way I have identified the "video" const with nextElementSibling seems to stop working. Or maybe something else is wrong, I am not sure.
I don't think forEach will help me here, at least as far as I understand how to use it.
One item in the grid looks like this:
<div class="videography__content--item">
<p class="video__title">Ноель Гоеман - Sanctus</p>
<div class="video__placeholder--container">
<img src="img/videography/noel-goemanne-sanctus.jpg" alt="" class="placeholder">
<div class="play-button"></div>
</div>
<iframe class="video-insert" src="https://www.youtube-nocookie.com/embed/BkRqCCkUku0"
title="YouTube video player" frameborder="0" allow="accelerometer; autoplay;
clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
And this is my JS code:
(function () {
const placeholder = document.querySelector(".video__placeholder--container");
const video = placeholder.nextElementSibling;
placeholder.addEventListener("click", switchToVideo);
function switchToVideo() {
placeholder.style.display = "none";
video.style.display = "block";
}
})();
I am sure there is some simple way to do it, but I am new to JS, so your help will be highly appreciated!
Problem solved with this code:
(function () {
const arrPictures = document.querySelectorAll(".video__placeholder--container");
const arrVideos = document.querySelectorAll(".video-insert");
arrPictures.forEach(function (el, index) {
el.addEventListener('click', () => switchToVideo(el, index))
});
function switchToVideo(el, index) {
el.style.display = "none";
arrVideos[index].style.display = "block";
}
})();