sppierce
sppierce

Reputation: 43

Vanilla Javascript: .forEach Loop Not Applying Event Listener

Looking for some support on why this loop is not applying the eventlisteners to the 2 image elements.

HTML:

<img src="video-embed.jpg" alt="text content">
<img src="video-embed-copy.jpg" alt="text content">

JAVASCRIPT:

let videoThumbnails = document.querySelectorAll('img[src*="video-embed"]');
    
function toggleGalleryModal(modal) {
    console.log(clicked);
    document.getElementById(modal).classList.toggle("show-modal");
}
    
function buildGalleryModals() {
    
    videoThumbnails.forEach(function (thumbnail, index) {
        let modalID = 'vid-gallery-modal-' + index,
            altText = thumbnail.alt;
    
        thumbnail.addEventListener('click', function (event) {
            console.log('thumbnail[i]: ' + index);
        });
    
        document.body.innerHTML += '<div id="' + modalID + '" class="vid-gallery-modal"><div class="modal-content"><span class="close-button">×</span>' + altText + '</div></div>';
    });
}
    
buildGalleryModals();

Upvotes: 0

Views: 2548

Answers (2)

crosen9999
crosen9999

Reputation: 823

The assignments inside the forEach() will not change the original array elements (i.e. videoThumbnails) as they operate on a copy of the array elements, and not the array elements themselves:

myArray = [1,2,3,4,5]

// try to assign new value to array elements using forEach
myArray.forEach(e => {
            e = '0';
            console.log(e);
        }
    )

// see that elements in original array are unchanged
myArray.forEach(e => {
            console.log(e);
        }
    )

Upvotes: 0

Scott Marcus
Scott Marcus

Reputation: 65873

The problem is that after you set up the click handlers, you overwrite the document.body.innerHTML with new HTML elements and wipe out the elements that you just set up.

Instead, inject that new HTML into a portion of the document, but not the document.body.

let videoThumbnails = document.querySelectorAll('img[src*="video-embed"]');

function toggleGalleryModal(modal) {
    console.log(clicked);
    document.getElementById(modal).classList.toggle("show-modal");
}

function buildGalleryModals() {

    videoThumbnails.forEach(function (thumbnail, index) {
        let modalID = 'vid-gallery-modal-' + index, 
            altText = thumbnail.alt;

        thumbnail.addEventListener('click', function (event) {
            console.log('thumbnail[i]: ' + index);
        });

        document.getElementById("output").innerHTML += '<div id="' + modalID + '" class="vid-gallery-modal"><div class="modal-content"><span class="close-button">×</span>' + altText + '</div></div>';
    });
}

buildGalleryModals();
<img src="video-embed.jpg" alt="text content1">
<img src="video-embed-copy.jpg" alt="text content2">
<div id="output"></div>

Upvotes: 2

Related Questions