Looking to create multiple image popups for different models using JavaScript? I am currently utilizing the W3Schools model image for this purpose

I am having trouble getting multiple image models to display, as only one pop-up is appearing. Can someone please assist me in figuring out how to show multiple pop-ups?

// Obtain the modal element
var modal = document.getElementById("myModal");

// Get the image and insert it into the modal - using its "alt" text as a caption
var img = document.getElementById("myImg");
var modalImg = document.getElementById("img");
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";
}
#myImg {
  border-radius: 5px;
  cursor: pointer;
  transition: 0.3s;
}

#myImg:hover {opacity: 0.7;}

/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  padding-top: 100px; /* Location of the box */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}

/* Modal Content (image) */
.modal-content {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
}

/* Caption of Modal Image */
#caption {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
  text-align: center;
  color: #ccc;
  padding: 10px 0;
  height: 150px;
}

/* Add Animation */
.modal-content, #caption {  
  -webkit-animation-name: zoom;
  -webkit-animation-duration: 0.6s;
  animation-name: zoom;
  animation-duration: 0.6s;
}

@-webkit-keyframes zoom {
  from {-webkit-transform:scale(0)} 
  to {-webkit-transform:scale(1)}
}

@keyframes zoom {
  from {transform:scale(0)} 
  to {transform:scale(1)}
}

/* The Close Button */
.close {
  position: absolute;
  top: 15px;
  right: 35px;
  color: #f1f1f1;
  font-size: 40px;
  font-weight: bold;
  transition: 0.3s;
}

.close:hover,
.close:focus {
  color: #bbb;
  text-decoration: none;
  cursor: pointer;
}

/* 100% Image Width on Smaller Screens */
@media only screen and (max-width: 700px){
  .modal-content {
    width: 100%;
  }
}
<h2>Image Modal</h2>
<p>In this example, we use CSS to create a modal (dialog box) that is hidden by default.</p>
<p>We use JavaScript to trigger the modal and to display the current image inside the modal when it is clicked on. Also note that we use the value from the image's "alt" attribute as an image caption text inside the modal.</p>
<img id="myImg" src="https://www.w3schools.com/howto/img_snow.jpg" alt="Snow" style="width:100%;max-width:300px">
<img id="myImg" src="https://www.w3schools.com/howto/img_snow.jpg" alt="Snow" style="width:100%;max-width:300px">

<!-- The Modal -->
<div id="myModal" class="modal">
  <span class="close">&times;</span>
  <img class="modal-content" id="img">
  <div id="caption"></div>
</div>

Answer №1

START OF ENHANCEMENT========>

I concur with @s.kuznetsov's comment about not recommending declaring JavaScript events within HTML tags. Therefore, I have provided a simple code snippet below that avoids declaring JavaScript events inside HTML tags and instead uses classes for images.

Add the class "gallery" to your image elements:

<img class="gallery" src="https://www.w3schools.com/howto/img_snow.jpg" alt="Snow1">

JavaScript code:

var modal = document.getElementById("myModal");
var span = document.getElementsByClassName("close")[0];
document.querySelectorAll('.gallery').forEach(function(gallery) {
    gallery.onclick = function(){
        var modalImg = document.getElementById("img");
        var captionText = document.getElementById("caption");
        modal.style.display = "block";
        modalImg.src = gallery.src;
        captionText.innerHTML = gallery.alt;
    }
});
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

<=======END OF ENHANCEMENT

You are using the same id for both images, which will cause issues. Below is an alternative JavaScript code that handles click events without relying on ids:

// Get the modal
var modal = document.getElementById("myModal");
function popupImage(image){
    // Get the image and insert it inside the modal - use its "alt" text as a caption
    var modalImg = document.getElementById("img");
    var captionText = document.getElementById("caption");
    modal.style.display = "block";
    modalImg.src = image.src;
    captionText.innerHTML = image.alt;

}
var span = document.getElementsByClassName("close")[0];

span.onclick = function() {
    modal.style.display = "none";
}
(CSS code omitted for brevity)
(<h2>Image Modal</h2> and image elements omitted for brevity)

Additionally, here is a jQuery implementation if you prefer:

var modal = $("#myModal");
$(document).on("click", "img.gallery", function(){
    $("img#img").attr('src',$(this).attr('src'));
    $("#caption").innerHTML = $(this).attr('alt');
    modal.show();
});
$(document).on("click","span.close",function(){modal.hide();});
(CSS code and html structure including the usage of jQuery omitted for brevity)

Answer №2

Consider utilizing classes instead of IDs since an ID must be unique for a single tag, whereas multiple tags can have the same class.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to Transfer Data from a Dynamic Drop-down Menu to PHP for Processing and Presentation in a Div Element on the Same Web Page

I've scoured various online resources, including StackOverflow, but haven't been able to find a solution for this issue described in the title. On my base page, I have a dynamically generated dropdown list as shown below: <div class="tipfixtu ...

HTML page filled to the brim with data tables

Wrapping up a midterm assignment for an HTML course and facing an issue on the final page. The table is overflowing to the right when the browser isn't maximized, and I'm stumped on how to solve it. Any suggestions? Unfortunately, unable to shar ...

Implement a jQuery DataTable using JSON data retrieved from a Python script

I am attempting to create an HTML table from JSON data that I have generated after retrieving information from a server. The data appears to be correctly formatted, but I am encountering an error with DataTable that says 'CIK' is an unknown para ...

Prevent automatic image blurring within an SVGZ file

Utilizing SVGZ images on my HTML pages for their ability to be resized. These SVGZ images consist of enlarged PNGs that have been altered in specific ways that I desire to maintain, pixelation and all. Firefox is rendering them correctly (as designed in In ...

Connect ng-include URL to certain paths

I am working with multiple routes in my application: routes.js $routeProvider.when( '/dashboard/one', { templateUrl: 'partials/dashboard.html', controller: 'DashboardCtrl' }); $routeProvider.when( '/da ...

If the condition is based on the category in category.php and single.php

I am attempting to create a conditional statement that will display specific content only if the user is in a particular category or on a single.php page associated with that category. I have experimented with these codes, but unfortunately, neither of the ...

React.js: The art of nesting components within each other

One common feature in many template languages is the use of "slots" or "yield" statements, which allow for a form of inversion of control by wrapping one template inside another. Angular offers the "transclude" option for this purpose. Ruby/Rails utilize ...

What's the best choice for ASP.NET: Using CSS or Themes?

What are the differences between using ASP.NET Themes and CSS for web design? When is it most beneficial to use each approach, and what are the advantages and disadvantages of one over the other? ...

Encountering difficulty with installing node_modules on Express js

Encountered an error while attempting to install node_modules from the package.json file. npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_em ...

Is it possible to center without specifying a fixed width?

Check out this demo link Is there a way to center all the divs and paragraphs under the main div without specifying a fixed width value? I want to remove the 300px width in the .center class and have all the elements align center. Specifically, how can I ...

Tips for transferring state from a component to the main screen in react-native

Struggling with passing state between components in a react-native application Let's consider the following scenario: MainScreen.js const MainScreen = () => { return ( <> <AdButton/> <Text>{adCreated}</Text> ...

What is the best way to use the copy files npm module to recursively copy all images from a source folder to a destination folder?

Is there a way to use the copy files command to transfer images (.png, .jpg) from an "src" folder to a "dist" folder while retaining the same filepaths internally and also ensuring it works recursively? https://www.npmjs.com/package/copyfiles I am curren ...

Android refuses to launch Google Play links from JavaScript in web applications

My HTML app is wrapped in Phonegap and available on the Android store. I want to include a link within the app for users to update it if a new version is available. From what I've gathered from documentation and some Stack Overflow posts, the follow ...

What could be the reason for the malfunction of jQuery's show() function?

Using jQuery, I have implemented a functionality to hide a div using the hide() method. However, upon clicking a link, the div is supposed to show but unexpectedly disappears after appearing briefly. HTML Code Snippet <div id="introContent"> & ...

Converting CSS styles with media queries and handling other special cases into a PHP array

Need help converting a CSS file to a PHP array. Here is the code snippet I am using: function convertCssToPhpArray($css_str) { $css = array(); // TODO: handle external css files $css_str = preg_replace('/(@import\s+["\'].+ ...

Clicking the jAuery selection button on the website allows

I have a table with buttons that I need to customize for selection, using CSS. The goal is to style the buttons differently than standard checkboxes or radio buttons by using the type "button" and applying CSS/CSS3 styles. <div class="button"> ...

Connecting Three.js graphics with a React functional component: A step-by-step guide

Is it appropriate to use the following code snippet in a functional React component that utilizes three.js? return ( <div key="0"> <p key="1">{ animate() }</p> </div> ) I have only seen examples o ...

Error throwing when attempting to use additional plugins in Angular CKEditor

I have been attempting to utilize the angular ckeditor extension found at: https://github.com/lemonde/angular-ckeditor UPDATE: I have already injected 'ckeditor' into the app modules. Within my partial html, I am including the following direc ...

Tips for updating the appearance of navigation bar links by changing text and background colors upon hover:

I need assistance changing the text color of my navigation bar links when hovering over them. The background is currently changing, but I want both the background and text to change simultaneously when hovered over. It seems to be working for the sub links ...

Retrieving the required Ng-checked checkbox (or radio button) in an ng-repeat loop within Angular framework

Looking for a way to validate a form that contains multiple radio checkboxes within an ng-repeat loop. How can I ensure the selected option is validated with the radio button input? Validation outside of the ng-repeat loop is functioning properly. For ex ...