Issues with creating modal images using only JavaScript

I am facing an issue with modal popup images. I have a collection of images and attempted to implement this code (with some modifications): https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal_img However, it seems to only work for the initial image displayed. How can I adjust it to function for all images within the gallery?

<div>
           <div class="portfolio-overlay">
                <img src="img/portfolio/Transeco-small.jpg">
                <div class="portfolio-image-overlay image-overlay-content">
                    <div class="portfolio-icons">
                         <i class="icon-zoom-in open-big"><img src="img/portfolio/Transeco-big.jpg" class="img-closed"></i>                          
                        <a href="http://www.google.com" target="_blank"><i class="icon-link"></i></a>
                    </div>
                </div>
            </div>
        </div>
        <div>
           <div class="portfolio-overlay">
                <img src="img/portfolio/Transeco-small.jpg">
                <div class="portfolio-image-overlay image-overlay-content">
                    <div class="portfolio-icons">
                         <i class="icon-zoom-in open-big"><img src="img/portfolio/Transeco-big.jpg" class="img-closed"></i>                          
                        <a href="http://www.google.com" target="_blank"><i class="icon-link"></i></a>
                    </div>
                </div>
            </div>
        </div>
        <div>
           <div class="portfolio-overlay">
                <img src="img/portfolio/Transeco-small.jpg">
                <div class="portfolio-image-overlay image-overlay-content">
                    <div class="portfolio-icons">
                         <i class="icon-zoom-in open-big"><img src="img/portfolio/Transeco-big.jpg" class="img-closed"></i>                          
                        <a href="http://www.google.com" target="_blank"><i class="icon-link"></i></a>
                    </div>
                </div>
            </div>
        </div>
<!-- The Modal -->
        <div class="modal myModal">
          <span class="close">&times;</span>
          <img class="modal-content img01">
        </div>


// Get the modal
var modal = document.querySelector(".myModal");

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.querySelector('.open-big');
var modalImg = document.querySelector(".img01");
var probaa = document.querySelector('.open-big img');
img.onclick = function(){
  modal.style.display = "block";
  modalImg.src = probaa.src;
}

// 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";
}

There are no errors in console, however, the functionality is limited to the first image...

Answer №1

const image = document.querySelector('.open-big');

document.querySelector is used to select a single element, specifically the first element with the class open-big

If you want to select all elements with that class, you should use document.querySelectorAll

Then, you can loop through the selected elements and add event listeners to each one:

const images = document.querySelectorAll('.open-big');

for (let i = 0; i < images.length; ++i) {
  images[i].onclick = function(){
    modal.style.display = "block";
    modalImg.src = probaa.src;
  }
}

It's important to note that normal array methods cannot be applied to a node collection. Therefore, images.forEach will not work. However, there is a workaround:

[].forEach.call(images, function(image) {
  // do something
});

For more information on this topic, visit this link on css tricks.

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

Updating a component when a prop changes

Embarking on my journey into the world of React, I find myself in need of assistance. The issue at hand involves re-rendering data within my Table component. Whenever a new API call is made to create an entry in my database using Prisma, the newly added d ...

The customCellFormatter function does not seem to be triggering for the dash_tabulator object

Currently, I am working on developing a Dash app using Python. My main focus is on utilizing a DashTabulator() object to present data. The requirement is to make specific columns editable and distinguish them by applying a unique background color (or text ...

What is the method for applying a Redux statement?

Experience with Redux toolkits: I've encountered an issue while working with Redux toolkits where I'm unable to access certain statements. I attempted the following code snippet, but it resulted in an error. const orderDetails = useSelector(( ...

Data modifications in polymer are not being accurately displayed

I need help with hiding/unhiding a UI element using a button in Polymer. Despite having the necessary elements and code set up, it is not working as expected: <button id="runPredictionButton"> <i>Button text</i> </button> <p ...

Guide on capturing JSON objects when the server and client are both running on the same system

I created an HTML page with a form that triggers JavaScript when submitted using the following event handler: onClick = operation(this.form) The JavaScript code is: function operation(x) { //url:"C:\Users\jhamb\Desktop\assignmen ...

Is there a way to remove the "next" button from the last page in a table?

I'm currently working on implementing pagination for my table. So far, I have successfully added both the "next" and "previous" buttons, with the "previous" button only appearing after the first page - which is correct. However, I am facing an issue w ...

`What is the best way to employ the Return statement in programming?`

Trying to grasp the concepts of functions and methods has been a challenge for me. I often find myself confused about when, where, and how to use return statements in different situations. To illustrate this confusion, let's take a look at two code sn ...

How do you vertically span a grid element across 3 rows using Material UI?

This particular scenario may appear to be straightforward, but the official documentation of Material UI lacks a clear example on how to achieve this. Even after attempting to nest the grid elements, I encountered an issue where the grid element on the ri ...

Ajax: The requested resource does not have the 'Access-Control-Allow-Origin' header. As a result, access is not permitted from origin 'null'

I recently started learning about ajax and followed a tutorial. However, I encountered an error when trying to run an HTML file along with a linked JavaScript file. Since browsers cannot make requests to file://, I have set up an http-server on port 8080 ...

Angular JS causing text alignment issues in table cells when viewed on mobile devices

I have created a web application that requires both desktop and mobile views, utilizing Angular JS. Everything is functioning as expected except for the text alignment within tables. I attempted using <td align="left">, but it did not produce any cha ...

How to turn off automatic formatting in CKEditor

Whenever data is entered into a field using CKEditor, the Save button becomes enabled. However, if I programmatically set data into the field using Javascript, the Change event always triggers causing the Save button to remain enabled even if the field is ...

Checking for duplicate entries in an array created with the Angular form builder

I am currently utilizing angular6 reactive form with form builder and form array. The issue I am encountering is duplicate subject entries from the drop down in the form array. How can I implement validation to prevent duplicate entries in the form array? ...

``There seems to be an issue with JQuery.Ajax not properly displaying on Samsung Smart

I attempted to use JQuery.Ajax to interact with my webservice Below is the code snippet: Main.onLoad = function() { // Enable key event processing this.enableKeys(); widgetAPI.sendReadyEvent(); //$("#h2Test").html("Change On Text"); ...

Tips for displaying an element for each item chosen in a multi-select box

I currently have a situation where I am rendering for every selected element within my multiselect angular material selectbox. The rendering process functions correctly when I select an element, but the issue arises when I try to deselect one - it just ke ...

Using NextJS getServerSideProps to Transfer Data to Page Component

Having trouble with my JavaScript/NextJS code, and not being an expert in these technologies. I'm using the method export const getServerSideProps: GetServerSideProps = async () => {} to fetch data from an integrated API within NextJS. The code mig ...

Loading items into the select menu

In my database, I have a table with 3 columns: ID, TITLE, TEXT. These will be used to populate select options in a form. When a user makes a selection, a script will take the title and text, make some adjustments, and store it in a different table. My que ...

Synchronous AJAX requests do not function properly in IE and Firefox, but they do work in Chrome and Safari

Attempting to measure download speed using an AJAX call. Below is the code snippet: var start = new Date(); $.ajax ({ url: 'https://www.example.com/perftest/dummyFile1024', cache: false, success : function() { var total = ( ...

AngularJs - Customizable dynamic tabs that automatically adapt

Below is the HTML code snippet: <div> <ul data-ng-repeat ="tab in tabs"> <li data-ng-class="{active: tab.selected == 'true'}" message-key="Tab"> </li> </ul> </div> As shown ...

Utilizing directives while initiating dynamic components

I've been exploring the capabilities of dynamically creating components using the ComponentFactoryResolver. const factory = this.componentFactoryResolver.resolveComponentFactory(FooComponent); const component = this.templateRoot. ...

Utilize the "incorporate" feature to include any string within an array

I am currently working on improving the search function in my application. This particular search function takes input from a search bar and is designed to handle multiple search terms. For example, it should be able to handle queries like "javascript reac ...