I'm trying to loop through 2 simple arrays of elements and add 'click' event listeners to them. For some reason, each item the event listener is added to fires 3 times on click. The length of the arrays is correct, and the js module is only being served once.
The intended behavior is to fire the function once when a thumbnail or title is clicked.
lightbox.js
export const lightbox = () => {
const thumbnails = document.querySelectorAll('.video-lightbox-gallery .thumbnail-wrapper');
const titles = document.querySelectorAll('.video-lightbox-gallery .video-title');
console.log(thumbnails.length) // 3
console.log(titles.length) // 3
setClickEvents(thumbnails)
setClickEvents(titles)
function setClickEvents(arr) {
arr.forEach(item => {
item.addEventListener('click', function() {
console.log('event fired')
})
})
}
}
main.js
document.addEventListener('DOMContentLoaded', () => {
if (document.querySelector('.video-lightbox-gallery')) {
import('./components/lightbox.js')
.then(module => {
module.lightbox()
})
}
})
video_lightbox_gallery.twig
<div class="video-lightbox-gallery">
<div class="container">
<div class="grid">
{% for video in gallery.videos %}
<div class="video-wrapper">
<div class="thumbnail-wrapper">
<div class="thumbnail" style="background-image: url('{{ Image(video.thumbnail).src }}');"></div>
<svg class="play-btn" data-name="Group 414" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 76.378 76.378"><g data-name="Ellipse 1" fill="#fff" stroke="#fff" stroke-width="1.5"><circle cx="38.189" cy="38.189" r="38.189" stroke="none"/><circle cx="38.189" cy="38.189" r="37.439" fill="none"/></g><path data-name="Polygon 1" d="m52.098 38.19-19.18 11.107V27.082Z" fill="#538d9c"/></svg>
</div>
<span class="video-title">{{ video.title }}</span>
</div>
<div class="video-lightbox-template">
<iframe src="{{ video.link }}?autoplay=1" title="{{ video.title }}" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
{% endfor %}
</div>
</div>
</div>