Image Modal only works with the first

3

I have a modal of images but it only works with the first, can anyone help me? see the modal here: link

    
asked by anonymous 18.11.2016 / 18:03

2 answers

8

The problem is that the two images have the same ID and is an attribute that must be unique. One option is to create any attribute and select the elements by querySelector :

It would look like this:

HTML

<img id="myImg1" get-img alt="Texto qualquer" width="300" height="200">
<img id="myImg2" get-img alt="Texto qualquer" width="300" height="200">

Javascript:

var imgs = document.querySelectorAll('[get-img]');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");

for (var i = 0 ; i < imgs.length ; i++){
  imgs[i].onclick = function(){
      modal.style.display = "block";
      modalImg.src = this.src;
      captionText.innerHTML = this.alt;
  }
}

JSFiddle : link

    
18.11.2016 / 18:07
4

The id is an attribute that should be assigned to only one element, change its code to use as the 'target' of the javascript image class.

The classes are used just to be able to interact with more than one element in the DOM.

var x = document.getElementsByClassName("example");

Something like that, in X are all elements with that class in an array, which begins with index 0.

    
18.11.2016 / 18:07