boo

Bootstrap modal images not working - Multiple


I just followed w3school tutorial for this bootstrap modal image. I have two image cards in my page. So I need to popup that two images. But it's working with one image only.

Link to w3school article

 <!-- Trigger the Modal -->

<img id="myImg" src="http://d14dsi4x2zx6ql.cloudfront.net/files/styles/welcome_image/public/VCW_TI_5_BayLoop_Hero_Manley_1280x642_sized.jpg?itok=EaARDZt8" alt="">

<!-- The Modal -->
<div id="myModal" class="modal">

  <!-- The Close Button -->
  <span class="close" onclick="document.getElementById('myModal').style.display='none'">&times;</span>

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

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

I insert "myImg" id in my other image, but it didn't work. First image popup worked as I expect. What will be missing here?


Solution

  • You can't give two elements the same id if you want to do the same action for both you can give them class

    <img class="myImg" src="http://placehold.it/850x450" alt="image1" width="200">
    <img class="myImg" src="http://placehold.it/700x400/f00" alt="image2" width="200">
    

    and js will be:

    // 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.getElementsByClassName('myImg');
    var modalImg = document.getElementById("img01");
    var captionText = document.getElementById("caption");
    //iterate over img to add click event for each one,, jquery will make it much easier
    for(var i=0;i< img.length;i++){
      img[i].onclick = function(){
          modal.style.display = "block";
          modalImg.src = this.src;
          captionText.innerHTML = this.alt;
      }
    }
    
    //jquery option
    /*$('.myImg').on('click', function(){
        modal.style.display = "block";
      modalImg.src = $(this).attr('src');
      captionText.innerHTML = $(this).attr('alt');
    })*/
    
    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("close")[0];
    

    Demo