Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 72443

Modify .js modal to make it work for several images

$
0
0

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?


Viewing all articles
Browse latest Browse all 72443

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>