pkc21
pkc21

Reputation: 37

Image modal that displays different image than the one clicked

I am following W3School's tutorial of how to create an image modal (https://www.w3schools.com/howto/howto_css_modal_images.asp). I am wondering if there is a way to edit the code they have so that when the image of the mountain is clicked, a different image gets displayed in the modal.

Context: I have an image with some text and a small graphic that when clicked I'd like to have a different image of a form be displayed in a modal.

Does anyone know if this is doable? Thanks.

Upvotes: 0

Views: 1430

Answers (1)

Ollie
Ollie

Reputation: 1435

Using the w3schools example you referenced, we can simply set the src of the modal image manually:

<!-- Trigger the Modal -->
<img id="myImg" src="img_snow.jpg" alt="Snow" style="width:100%;max-width:300px">

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

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

  <!-- Modal Content (The Image) -->
  <img class="modal-content" src="your-image.jpg">

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

Then we can adjust the JavaScript so the src attribute is not overriden:

// 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("myImg");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
  modal.style.display = "block";
  //  modalImg.src = this.src; <- Remove this line!
  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";
}

Upvotes: 1

Related Questions