Issue with opening image modal when clicking on images, JavaScript seems to be malfunctioning

I created a gallery of modal images that I want to open when clicked, but for some reason it's not working as expected. What I'm trying to achieve is passing the image ID of each image to JavaScript when they are clicked so that the script can then open the corresponding image in a popup or modal with a close button.

Here's the CSS code:

<style>
/* The grid: Four equal columns that float next to each other */
.column {
  float: left;
  width: 25%;
  padding: 10px;
}

/* Styling for the images inside the grid */
.column img {
  opacity: 0.8; 
  cursor: pointer; 
}

.column img:hover {
  opacity: 1;
}

/* Clear floats after the columns */
.row:after {
  content: "";
  display: table;
  clear: both;
}

/* Container for the expanding image */
.imgcontainer {
  position: relative;
  display: none;
}
// Additional styles for the modal and close button
...

</style>

And here's the HTML code:

<div id="myModal" class="modal">
  ...      
</div>

<div class="row">
  ...  
</div>    

</div>
</div>

Finally, the JavaScript code looks like this:

<script>
function myFunction(imgs) {
...
};

</script>

Answer №1

After making some revisions, your code is now updated. I have incorporated two distinct functions - one for initiating and adjusting the src attribute of the modal based on user interaction, and another for closing the modal.

function showImage(event) {
  var modal = document.getElementById("myModal");
  modal.style.display = "block";
  document.getElementById("expandedImg").setAttribute('src', event.target.getAttribute("src"));

}

function hideModal(event) {
  const modal = document.getElementById("myModal");
  modal.style.display = "none";
}
/* Define a grid layout with four equal columns that float side by side */
.column {
  float: left;
  width: 25%;
  padding: 10px;
}

/* Customize images within the grid */
.column img {
  opacity: 0.8;
  cursor: pointer;
}

.column img:hover {
  opacity: 1;
}

/* Clear floating elements after the columns */
.row:after {
  content: "";
  display: table;
  clear: both;
}

/* Container for expanding images */
.imgcontainer {
  position: relative;
  display: none;
}



/* Close button in the expanded image */
.closebtn {
  position: absolute;
  top: 15px;
  right: 35px;
  color: #f1f1f1;
  font-size: 40px;
  font-weight: bold;
  transition: 0.3s;
}

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


.modal {
  display: none;
  /* Initially hidden */
  position: fixed;
  /* Fixed position */
  z-index: 1;
  /* Top layer */
  padding-top: 100px;
  /* Positioning */
  left: 0;
  top: 0;
  width: 100%;
  /* Full width */
  height: 100%;
  /* Full height */
  overflow: auto;
  /* Enable scrolling if necessary */
  background-color: rgb(0, 0, 0);
  /* Fallback color */
  background-color: rgba(0, 0, 0, 0.9);
  /* Black background with opacity */
}

.modal-content {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
}


/* Add Animation */
.modal-content {
  -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)
  }
}
<!-- Insert your HTML here -->
<div id="myModal" class="modal">
  <span class="closebtn" onclick="hideModal(event)">&times;</span>
  <img class="modal-content" id="expandedImg">
</div>

<!-- The four columns -->
<div class="row">
  <div class="column">
    <img src="img/content/services/serv-71.jpg" alt="Nature" style="width:100%" onclick="showImage(event);">
  </div>
  <div class="column">
    <img src="img/content/services/serv-72.jpg" alt="Snow" style="width:100%" onclick="showImage(event);">
  </div>
  <div class="column">
    <img src="img/content/services/serv-73.jpg" alt="Mountains" style="width:100%" onclick="showImage(event);">
  </div>
  <div class="column">
    <img src="img/content/services/serv-74.jpg" alt="Lights" style="width:100%" onclick="showImage(event);">
  </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

Utilize the CSS content property to embed an image without causing it to distort in size

Struggling to swap out one image for another without stretching it? In my demo, I replaced an elephant with a lion using only CSS - no changes allowed to the HTML. Unfortunately, the lion image ends up stretched. Even adding background-size: cover doesn&ap ...

Exploring Vue.js: Navigating through child components from parent component

I currently have 3 components in my project: Form, Card, and Button. Let's start with the Button.vue component: <template> <div> <slot v-bind="{ text }"> <button>{{ text }}</button> </slot> ...

What is the best way to increase the height of a div up to a specific point before allowing it to scroll?

Is there a way to make a div expand to fit its contents up to 250px and then scroll if necessary? I attempted using the following CSS: text-overflow: ellipsis; max-height: 250px; overflow-y: scroll; However, this solution doesn't achieve the desired ...

Guide to organizing files with custom directory layout in NodeJS

Imagine having multiple files spread across various folders. /parentDir/ |__dirA/ |__file1 |__file2 |... |__dirB/ |__file3 |... |... You want to consolidate them into an archive, with the option of using something like ...

"Having trouble getting `justify-between` to work in a tailwind CSS on an absolute

I'm currently using Tailwind CSS and I'm trying to position my navbar on top of an image. The image is set in a relative position and the navbar is set in an absolute position. Surprisingly, when the navbar is not set in the absolute position, I ...

Troubleshooting a MySQL problem with updating a large quantity of HTML content

I've integrated autosave functionality using Ajax into my content management system. However, I've encountered a problem. The issue arises when I test the system on my local server - the PHP side updates large amounts of data smoothly. But when I ...

Store and retrieve user input using JavaScript or JSON

Can someone please assist me in finding a solution to this problem? I have 3 input fields where users can type in their answers. There is also a "SAVE" button that allows users to download their input values into a file.txt. Additionally, there is a "choos ...

Troubleshooting: Issue with binding nested data property using bracket access in Vue3 v-model

Having an issue in Vue3 where I am unable to bind a nested property to v-model correctly. Check out the source code below: Template: <div id="app"> <span>{{level1.level2.level3}}</span> <br/> <span>{{level1[&ap ...

Creating a dynamic multi-level menu within a hamburger menu

Tackling the challenge of creating a hamburger multi-level menu for a web page using CSS has proven to be quite tricky. The main issue I'm encountering is successfully incorporating a sub-menu to make it truly multi-level. Here's the progress I&a ...

Adding additional elements to a div in a horizontal orientation

I am currently working on a project where I need to display bars and restaurants based on specific filter criteria. I have a container div called .resultsContainer where all the results will be displayed. While I can easily append more divs (.barContainer) ...

iOS Simulator offers a range of both offline and online events for testing purposes

I have been working on a phonegap 3.3 application that incorporates angularjs. When testing the application in my browser, I am successfully able to detect and respond to 'offline' and 'online' events. However, when I switch to the ios ...

Ways to distinguish jquery response apart from using $.post method?

Using jquery $.post method: $.post( 'includes/studiesAjax/addTryb.php', {inputVL: inputVL}, function(res){ $("#container").html(res); } ); The response contains a long html code. I am interested in extracting data from ...

Retrieve distinct keys from a JSON file in Node.js

Below is an example of JSON data: [ { "Name": "User1", "primaryRegion": "US" }, { "Name": "user2", "primaryRegion": "US" }, { "Name": &q ...

A step-by-step guide on using Jquery to fade out a single button

My array of options is laid out in a row of buttons: <div class="console_row1"> <button class="button">TOFU</button> <button class="button">BEANS</button> <button class="button">RIC ...

Is it possible to utilize Angular's $http.get method with a dynamic route

I recently started working with Angular and I'm trying to figure out how to retrieve data from a REST API using a scope variable to determine the URI for the GET request. Imagine that I have an array of numbers being generated by a service in my app ...

What is causing ui-route to fail in resolving state1 when transitioning from state2?

I have a program that consists of two views (lefthandmenu and content), with modules. When the user selects a module from a combo-list, $state.go() is called with the selected module name, and the views should update accordingly. See code samples below. I ...

Is it possible to activate events on select tags even when they have the disabled attribute?

All the select options on this page have been disabled with an ID that ends in _test, and everything seems to be functioning properly. However, I would like to display a title when the selects are disabled and the mouse hovers over them. The issue arises ...

The layout of the keyboard in Cordova has been altered

Just starting out with my first Cordova app and I'm working on a simple login form. The issue I'm facing is that whenever I click on an input element, the keyboard pops up and completely messes up my layout, which should be straightforward. Has ...

Dynamically populate content on render in Vue.js based on the vue.router parameters

Can anyone help me understand why I'm receiving unexpected results? I am using v2 vue.js. In my project, I have a single file component for a Vue component. The component is supposed to render data imported from "excerciseModules" in JSON format. Th ...

Validating Dropzone JS upon submission

I'm working on a form that utilizes dropzone.js for file upload. While I'm successfully validating all the input fields, I'm facing an issue with validating the file upload before submission. I want the submission to proceed only if a file i ...