I am looking to create an engaging photo viewing experience by utilizing a modal to display each image in my gallery when clicked

I created a stunning image gallery featuring 13 photos that I discovered on W3Schools and customized to suit my own preferences. The gallery looks great, but there's an issue - only the first image can be opened using a modal window. I tried editing some JavaScript code snippets found on W3Schools, but they only work for the first image and not the rest. As someone new to working with JavaScript, I am eager to enhance the functionality so that each image in the gallery can be opened in a modal window when clicked or touched.

This is the code snippet I am currently using:

// 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("image-gall-1");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption-gallery-fu-sc");
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-gallery-fu-sc")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() { 
  modal.style.display = "none";
}

Answer №1

To ensure proper functionality, it is crucial to target each individual img element within your gallery, rather than just a specific id.

var img = document.querySelectorAll(".column img");

You should then iterate over these images using a loop:

img.forEach((imgA)=>{
    imgA.onclick = function(){
      modal.style.display = "block";
      modalImg.src = this.src;
      captionText.innerHTML = this.alt;
    }
});

// Accessing the modal
var modal = document.getElementById("myModal");
// Finding and placing the image inside the modal - utilizing its "alt" text as a caption
var img = document.querySelectorAll(".column img");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption-gallery-fu-sc");

img.forEach((imgA)=>{
    imgA.onclick = function(){
  modal.style.display = "block";
  modalImg.src = this.src;
  captionText.innerHTML = this.alt;
}
});

// Closing modal when clicking on close button
var span = document.getElementsByClassName("close-gallery-fu-sc")[0];
span.onclick = function() { 
  modal.style.display = "none";
}
.row {
  display: -ms-flexbox; /* For IE 10 */
  display: flex;
  -ms-flex-wrap: wrap; /* For IE 10 */
  flex-wrap: wrap;
  padding: 0 4px;
}

/* Creating two columns that sit next to each other */
.column {
  -ms-flex: 50%; /* For IE 10 */
  flex: 50%;
  padding: 60px 4px;
}

.column img {
  margin-top: 8px;
  vertical-align: middle;
}
/* Styling the Image Used to Trigger the Modal */
#image-gall-1,#image-gall-2,#image-gall-3,#image-gall-4,#image-gall-5,#image-gall-6,#image-gall-7,#image-gall-8,#image-gall-9,#image-gall-10,#image-gall-11,#image-gall-12,#image-gall-13 {
  border-radius: 5px;
  cursor: pointer;
  transition: 0.3s;
}
#image-gall-1:hover, #image-gall-2:hover, #image-gall-3:hover, #image-gall-4:hover, #image-gall-5:hover,#image-gall-6:hover, #image-gall-7:hover, #image-gall-8:hover, #image-gall-9:hover, #image-gall-10:hover, #image-gall-11:hover, #image-gall-12:hover, #image-gall-13:hover {opacity: 0.7;}
/* The Modal (background) */
.modal-gallery-fu-sc {
  display: none; /* Initially hidden */
  position: fixed; /* Fixed position */
  z-index: 1; /* On top of other elements */
  padding-top: 100px; /* Positioning */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.9); /* Black with opacity */
}
... (CSS omitted for brevity)
<div class="container">
<!-- The Modal -->
<div id="myModal" class="modal-gallery-fu-sc">
  <!-- The Close Button -->
  <span class="close-gallery-fu-sc">×</span>
  <!-- Modal Content (The Image) -->
  <img class="modal-content-gallery-fu-sc" id="img01">
  <!-- Modal Caption (Image Text) -->
  <div id="caption-gallery-fu-sc"></div>
</div>

<!-- Photo Grid -->
<div class="row"> 
  <div class="column">
    <img id="image-gall-1" src="https://www.w3schools.com/w3images/wedding.jpg" alt="wedding" style="width:100%">
    ... (Additional image entries omitted for brevity)
  </div>
  <div class="column">
    ... (Additional image entries omitted for brevity)
  </div>
</div>
</div>

Answer №2

Only the first image has a click event listener, which is why the modal doesn't open when clicking on other images. To fix this issue, you can add event listeners to all images by giving them a common class name and using a loop to iterate through each image.

var images = document.getElementsByClassName("image-gall");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption-gallery-fu-sc");    
for (var i = 0; i < images.length; ++i) {
    var img = images[i];
    img.onclick = function() {
        modal.style.display = "block";
        modalImg.src = this.src;
        captionText.innerHTML = this.alt;
    }
}
.row {
    display: -ms-flexbox;
    display: flex;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    padding: 0 4px;
}

.column {
    -ms-flex: 50%;
    flex: 50%;
    padding: 60px 4px;
}

.column img {
    margin-top: 8px;
    vertical-align: middle;
}

#image-gall-1,#image-gall-2,#image-gall-3,#image-gall-4,#image-gall-5,#image-gall-6,#image-gall-7,#image-gall-8,#image-gall-9,#image-gall-10,#image-gall-11,#image-gall-12,#image-gall-13 {
    border-radius: 5px;
    cursor: pointer;
    transition: 0.3s;
}

/* Add more styling if needed */

.modal-gallery-fu-sc {
    /* Modal styles */
}

.modal-content-gallery-fu-sc {
    /* Modal content styles */
}

/* Add more CSS as required */

<div class="container">
    <div id="myModal" class="modal-gallery-fu-sc">
        <span class="close-gallery-fu-sc">×</span>
        <img class="modal-content-gallery-fu-sc" id="img01">
        <div id="caption-gallery-fu-sc"></div>
    </div>

    <div class="row"> 
        <div class="column">
            <img id="image-gall-1" class="image-gall" src="image1.jpg" alt="Image 1" style="width:100%">
            <!-- Add more images here with similar markup -->
        </div>

        <div class="column">
            <img id="image-gall-2" class="image-gall" src="image2.jpg" alt="Image 2" style="width:100%">
            <!-- Add more images here with similar markup -->
        </div>
    </div>
</div>

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

Implementing a Dynamic Background Color Switcher in React

I'm currently working on creating a function that will alter the background color of a website's homepage when a user clicks a specific button. class App extends Component { constructor(props) { super(props); this.state = { quote ...

Allow one child to be visible even if the parent container has hidden overflow (or a different setting)

Is there a way to achieve the same look as shown in this example, but without repeating the border-radius code for the div.left in the CSS? It feels redundant and I suspect my approach may not be optimal. If you have any suggestions on how to accomplish t ...

Converting Emoji to PNG or JPG using Node.js - What's the Procedure?

Currently, I am working on a project that requires me to create an image file from emoji characters, preferably using Apple emoji. Initially, I thought this task would be simple to accomplish, but I have encountered obstacles with each tool I have tried. ...

What steps can I take to ensure my CSS component remains unaffected by the global CSS styles?

My navbar component is not displaying the styles correctly as intended. I have a Navbar.module.css file to style it, but after using next-auth for social login, only the buttons remain unstyled while everything else gets styled. The code snippet for impor ...

Difference among rows

I am currently working on a table design with 2 rows that have different colors. There seems to be some space between the two rows and I am looking for a way to eliminate that gap. Can anyone provide me with a solution? https://i.stack.imgur.com/8N8Rw.png ...

IE is failing to trigger jAlert function

When I validate a text box by pressing the enter key on my keyboard, the validation works fine but the JAlert doesn't show up. However, when I call the same function on a button click, the alert shows in IE. I am quite confused by this behavior and wo ...

Searching for specific elements within a certain range based on their

I currently have a table that consists of rows and columns, each containing specific attributes: <tr attr-y="1"><td attr-x="1">...</td><td attr-x="2">...</td>...</tr> <tr attr-y="2"><td attr-x="1">...</td ...

Element dynamically targeted

Here is the jQuery code I currently have: $('.class-name').each(function() { $(this).parent().prepend(this); }); While this code successfully targets .class-name elements on page load, I am looking to extend its functionality to also target ...

Is there a way to split each foreach value into distinct variables?

I am looking to assign different variables to foreach values. I have fetched data from an API in JSON format, and then echoed those values using a foreach loop. My goal is to display the echoed value in an input box using JavaScript. I attempted the follow ...

Trouble with CSS styling for focused input fields

Attempting to style a form by Patriot with CSS, I encountered an issue. input#card-month:focus ~ label.card-label.label-cardExpiryYear { font-size: 20px !important; /* This works fine */ } input#card-month:focus ~ label.card-label.label-cardExpiryMont ...

What is the best way to combine MVVM, offline storage, and Knockout.js in a project?

Although I have experience with implementing Mvvm using Knockout.js, my goal now is to incorporate this framework with cross-browser support for Firefox and Chrome along with HTML5 offline storage capabilities. Specifically, I am looking to bind HTML obje ...

Having Trouble with Unevenly Spaced Child Elements in CSS Flexbox?

I'm running into a problem while utilizing CSS Flexbox to design a layout with multiple child elements. The issue at hand is that the child elements are not aligning correctly within the parent container. I aim for them to be evenly distributed and ce ...

Incorporate Videos into HTML Dynamically

Is there a way to dynamically embed videos from a source into an HTML page? My goal is to make it easy to add new videos to the page by simply placing them in a folder and having them automatically embedded. I am wondering if this can be achieved using J ...

Creating a Precise Millisecond Countdown Timer using Angular 4 in Javascript

I'm currently facing a challenge in Angular 4 as I attempt to develop a countdown timer that accurately displays milliseconds once the timer falls below 1 minute (59 seconds or less) for a sporting event clock. My issue lies with the setInterval funct ...

Automatically displaying the navigation bar upon initial loading of the HTML page

Is there a way to adjust this code so that the side nav bar remains open when the page loads for the first time? I would like the side nav to be open by default. function openNav() { document.getElementById("mySidenav").style.width = "250px"; docum ...

Having trouble uploading an image to firebase storage as I continuously encounter the error message: Unable to access property 'name' of undefined

Hey there, I'm currently facing an issue while trying to upload an image to Firebase storage. Despite following all the instructions on the official Firebase site, I'm stuck trying to resolve this error: Uncaught TypeError: Cannot read property ...

At what point will the browser display changes made to css using jQuery?

When I run my JavaScript code in Firebug, it looks like this: tr=$(this).parent('tr'); tr.find('.img-delete').css('display','block'); However, I am unable to see the change reflected on the browser. Is there a wa ...

Can you determine the height of an image if only the width and border width are provided?

Currently delving into the world of HTML and CSS, I've successfully configured the img element's width and border width using a style element. However, one aspect that is still puzzling me is how the height is calculated in this scenario. I&apos ...

Is there a way to remove the bold styling from text next to JavaScript?

I recently launched a website at www.mvscaccounting.com, and I added a search engine made from javascript at the bottom of the page. Next to it, I wanted to put a "all rights reserved" notice. However, whenever I try to add any text next to the search engi ...

The jQuery.addClass() function seems to be malfunctioning

I'm encountering an issue with the addClass() method. For some reason, it's not functioning properly in this scenario: https://jsfiddle.net/0g1Lvk2j/20/ If you scroll to the end and close the last box by clicking on the orange box, the orange b ...