Rumturf
Rumturf

Reputation: 86

Modify .js modal to make it work for several images

I found this piece of code online to make a modal (popup) with an enlarged picture, when clicking on the thumbnail. The code is shown below and it uses the unique element ID of the thumbnail.

I want to adapt this code so it works for every thumbnail without having to create unique ID's and multiple modals.

Here is the original code using html elements' ID:

var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
  modal.style.display = "block";
  modalImg.src = this.src;
  captionText.innerHTML = this.alt;
}

I tried to turn this into working with classes. I realised that getElementsByClassName probably contains multiple items and put the into a list, so I added a for-loop:

var imgs = document.getElementsByClassName("tabs-img");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
for (var img in imgs) {
    img.onclick = function(){
        modal.style.display = "block";
        modalImg.src = this.src;
        captionText.innerHTML = this.alt;
    }
}

However, when clicking the thumbnails, nothing happens.

What is wrong with my adaptation?

Upvotes: 1

Views: 30

Answers (1)

wlh
wlh

Reputation: 3525

The Web API getElementsByClassName returns an HTMLCollection.

But you cannot use a for...in loop to iterate the items of an HTMLCollection, rather, you can use either a regular for or a for...of loop.

An HTMLCollection is not an Array, but is Array-like https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection. It has additional properties and methods that interferes with for...in. See the accepted answer here -> For loop for HTMLCollection elements

Change your loop to for...of which can iterate over array-like objects: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

for (var img of imgs) {
  img.onclick = function(){
    modal.style.display = "block";
    modalImg.src = this.src;
    captionText.innerHTML = this.alt;
  }
}

Upvotes: 1

Related Questions