How do I get this script to work on more than one element ... A Newbie?

Hi,

I am trying to get this script to work on more than one image on a page what do I have to do to change it to have it apply to more than mapImg and img01. I am assuming that those are the areas of the script that need to be modified … But this is the first js that I have worked with …

Thanks,
David Engstrom

// Get the modal
var modal = document.getElementById('myModal');

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById('mapImg');
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;
}

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span.onclick = function() { Preformatted text
  modal.style.display = "none";
}

You’ll need to make your selectors more generic. Right now the script is using getElementById, which will select just those elements which have the attributes of id=“something” (ex id=“mapImg”)

If you want to do somethimg more generic, then you’ll need to use something like

These two methods will return an array containing all the elements. You will then have to loop through each iteration to apply your logic (the links provided have some decent code to get you started…)

2 Likes

As Dave says, the script needs to collect the target images and apply the onclick handler to each one. The following script gives one way to do it.

<script type="text/javascript">
// collect the image objects 
 var i, everyImg, modal, modalImg, captionText;
 everyImg=document.getElementById("imgAll").getElementsByTagName("img");
 modal = document.getElementById('myModal');
 modalImg = document.getElementById("img01");
 captionText = document.getElementById("caption");
 for(i=0; i<everyImg.length; i++){ everyImg[i].onclick = process; }
// ---------
function process(){  
  modal.style.display = "block";    
  modalImg.src = this.src;
  captionText.innerHTML = "<span id='close'>Close<\/span>&nbsp; "+this.alt+""; 
  document.getElementById("close").onclick=function(){ modal.style.display="none"; };
    }
 //    
</script>

There is a working example on JSFiddle HERE.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.