Search code examples
javascriptmodal-dialogselectorgetelementbyid

Select Multiple Elements for Image Modal


I want to use a selector to select every image on the page for putting into the modal without rewriting the entire script for each image. I feel like this a is a dumb question but I keep striking out trying different things. Right now I'm using var img = document.getElementById("article01"); to select one image because that's all you can do with getElementById. So I want to select both the images listed so that I'm not rewriting the entire script for each image because there will be many more on the page. I tried using getelementbyclass and tagname but I think I'm stuck.

HTML:

<!-- Trigger the Modal -->
    <img id="article01" src="/images/article1.PNG" alt="" style="width:100%;max-width:300px">
    <img id="article01-2" src="/images/article1-2.PNG" alt="" style="width:100%;max-width:300px">
<!-- The Modal -->
    <div id="modal1" class="modal">

    <!-- The Close Button -->
    <span class="close">&times;</span>

    <!-- Modal Content (The Image) -->
    <img class="modal-content" id="img01">

    <!-- Modal Caption (Image Text) -->
    <div id="caption"></div>
</div>

Javascript:

    <script>
    // Get the modal
    var modal = document.getElementById("modal1");

    *var img = document.getElementById("article01");*
    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() {
        modal.style.display = "none";
    }

</script>

Solution

  • You can use document.querySelectorAll() to get a nodeList of all of the images. For example, if you created your list of images as such:

    <img class="selectable" src="article-1" />
    <img class="selectable" src="article-2" />
    <img class="selectable" src="article-2" />
    

    You can add an event listener to each using ...

    document.querySelectorAll('img.selectable')
      .forEach((img) => {
        img.addEventListener('click', (e) => showModal(e.target)); //or use img.onclick = ...
      });
    

    Here is a link to a CodePen showing a demo of how to do this...