Tips for dynamically loading a modal

Hello, I am curious about dynamically loading modals on different images within my current webpage.

https://i.sstatic.net/yhTgs.png

For example, when the life of Pi image is clicked, a modal pops up displaying relevant information.

https://i.sstatic.net/VcTPE.png

I would like this functionality to extend to other images as well. Clicking on the Kite Runner image should open a modal with the image on the left and text on the right.

This is my existing code:

$(document).ready(function() {
      var $modal = $("#myModal");
      $("#lifeofpi").click(function() {
        $modal.show();
      });
      $modal.find('.close').click(function() {
        $modal.hide();
      });
    });
/* 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.7); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 700px;
height: 500px;
background-color: #101010;

}


/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}

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

  

.modallifeofpi {
 cursor: pointer;
 height: 160px; // height
 //width: 30%; // width
 border: 5px solid white;
 display: inline;
 margin-top:0px;
 position: absolute;
 }


 .modalheader {
 color:white;
 margin:0;
 margin-left: 470px;

 }

 .modalheadertext {
 color:white;
 margin-left: 350px;
 margin-top:40px;
 }
  
 .review-img {
  cursor: pointer;
  height: 160px; // height
  //width: 30%; // width
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class='images'>
<img class="review-img" id="lifeofpi" src="https://images-na.ssl-images-amazon.com/images/I/51atapp7YTL._AC_US320_QL65_.jpg" alt="lifeofpi"></img>
<img class="review-img" id="kiterunner" src="https://images-na.ssl-images-amazon.com/images/I/51MtGFNeYjL._AC_US320_QL65_.jpg" alt="kiterunner"></img> </img>
<img class="review-img" id="starwars" src="https://images-na.ssl-images-amazon.com/images/I/51oqkfvEwZL._AC_US320_QL65_.jpg" alt="starwars"></img>
<img class="review-img" id="twilight" src="https://images-na.ssl-images-amazon.com/images/I/41K99+cInvL._AC_US320_QL65_.jpg" alt="twilight"></img>
</section>

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

  <img class="modallifeofpi" src="https://images-na.ssl-images-amazon.com/images/I/51atapp7YTL._AC_US320_QL65_.jpg" alt="lifeofpi"></img>
  <h1 class="modalheader">Life of pi</h1>
  <h2 class="modalheadertext">Published:</h2>
   </div>
</div>

Answer №1

To display images in a modal, you can bind all the images and pass their information to the modal using jQuery.

$(document).ready(function() {
      var $modal = $("#myModal");
      $(".images img").click(function() {
    $modal.find('img.modallifeofpi').attr('src',$(this).attr('src'));
    $modal.find('.modalheader').text($(this).attr('alt'));
    $modal.show();
});
$modal.find('.close').click(function() {
    $modal.hide();
});
    });
/* CSS for the modal */
.modal {
display: none; 
position: fixed; 
z-index: 1;
padding-top: 100px; 
left: 0;
top: 0;
width: 100%; 
height: 100%;
overflow: auto; 
background-color: rgb(0,0,0); 
background-color: rgba(0,0,0,0.7); 
}

/* Styling for the modal content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 700px;
height: 500px;
background-color: #101010;

}


/* Close button styling */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}

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

  

.modallifeofpi {
 width: 300px;
 height: 450px;
 border: 5px solid white;
 display: inline;
 margin-top:0px;
 position: absolute;
 }


 .modalheader {
 color:white;
 margin:0;
 margin-left: 470px;

 }

 .modalheadertext {
 color:white;
 margin-left: 350px;
 margin-top:40px;
 }
  
 .review-img {
  cursor: pointer;
  height: 160px; 
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class='images'>
<img class="review-img" id="lifeofpi" src="https://images-na.ssl-images-amazon.com/images/I/51atapp7YTL._AC_US320_QL65_.jpg" alt="lifeofpi"></img>
<img class="review-img" id="kiterunner" src="https://images-na.ssl-images-amazon.com/images/I/51MtGFNeYjL._AC_US320_QL65_.jpg" alt="kiterunner"></img> </img>
<img class="review-img" id="starwars" src="https://images-na.ssl-images-amazon.com/images/I/51oqkfvEwZL._AC_US320_QL65_.jpg" alt="starwars"></img>
<img class="review-img" id="twilight" src="https://images-na.ssl-images-amazon.com/images/I/41K99+cInvL._AC_US320_QL65_.jpg" alt="twilight"></img>
</section>

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

  <img class="modallifeofpi" src="./images/lifeofpi.jpg"></img>
  <h1 class="modalheader">Life of pi</h1>
  <h2 class="modalheadertext">Published:</h2>
   </div>
</div>

Answer №2

Utilize classes as selectors to set image sources as attributes on the images. Additionally, other fields can be populated in a similar manner

$(document).ready(function() {
    var $modal = $("#myModal");
    $(".modal-img").click(function() {
        $modal.find('img.modallifeofpi').attr('src',$(this).attr('img-src'));
        $modal.find('.modalheader').text($(this).attr('img-title'));
        $modal.show();
    });
    $modal.find('.close').click(function() {
        $modal.hide();
    });
});

and HTML :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class='images'>
<img class="review-img modal-img" id="lifeofpi" src="https://images-na.ssl-images-amazon.com/images/I/51atapp7YTL._AC_US320_QL65_.jpg" img-title="Life of pi" img-src="./images/lifeofpi.jpg" alt="lifeofpi"></img>
<img class="review-img modal-img" id="kiterunner" src="https://images-na.ssl-images-amazon.com/images/I/51MtGFNeYjL._AC_US320_QL65_.jpg" img-title="Kite Runner" img-src="./images/kiterunner.jpg" alt="kiterunner"></img> </img>
<img class="review-img modal-img" id="starwars" src="https://images-na.ssl-images-amazon.com/images/I/51oqkfvEwZL._AC_US320_QL65_.jpg" img-title="Star Wars" img-src="./images/starwars.jpg" alt="starwars"></img>
<img class="review-img modal-img" id="twilight" src="https://images-na.ssl-images-amazon.com/images/I/41K99+cInvL._AC_US320_QL65_.jpg" img-title="Twinlight" img-src="./images/twinlight.jpg" alt="twilight"></img>
</section>

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

  <img class="modallifeofpi" src=""></img>
  <h1 class="modalheader">Life of pi</h1>
  <h2 class="modalheadertext">Published:</h2>
     </div>
</div>

Answer №3

Copy the attributes from img to modal and then show the modal. See example below.

$(document).ready(function() {
  var $modal = $("#myModal");
  var src = "";

  $('.images img').click(function() {
    $img = $(this);
    $modal.find('img').attr('src', $img.attr('src'));
    $modal.find('.modalheader').text($img.attr('alt'));
    $modal.show();
  });


  $('#myModal .close').click(function() {
    $modal.hide();
  });
});
/* The Modal (background) */

.modal {
  display: none;
  /* Default hidden */
  position: fixed;
  z-index: 1;
  padding-top: 100px;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0, 0, 0);
  background-color: rgba(0, 0, 0, 0.7);
}


/* Modal Content */

.modal-content {
  background-color: #fefefe;
  margin: auto;
  padding: 20px;
  border: 1px solid #888;
  width: 700px;
  height: 500px;
  background-color: #101010;
}


/* The Close Button */

.close {
  color: #aaaaaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

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

.review-img {
  cursor: pointer;
}

.modallifeofpi {
  width: 300px;
  height: 450px;
  border: 5px solid white;
  display: inline;
  margin-top: 0px;
  position: absolute;
}

.modalheader {
  color: white;
  margin: 0;
  margin-left: 470px;
}

.modalheadertext {
  color: white;
  margin-left: 350px;
  margin-top: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<section class='images'>
  <img class="review-img" id="lifeofpi" src="https://images-na.ssl-images-amazon.com/images/I/51atapp7YTL._AC_US320_QL65_.jpg" alt="lifeofpi" />
  <img class="review-img" id="kiterunner" src="https://images-na.ssl-images-amazon.com/images/I/51MtGFNeYjL._AC_US320_QL65_.jpg" alt="kiterunner" />
  <img class="review-img" id="starwars" src="https://images-na.ssl-images-amazon.com/images/I/51oqkfvEwZL._AC_US320_QL65_.jpg" alt="starwars" />
  <img class="review-img" id="twilight" src="https://images-na.ssl-images-amazon.com/images/I/41K99+cInvL._AC_US320_QL65_.jpg" alt="twilight" />
</section>

<!-- The Modal -->
<div id="myModal" class="modal">
  <!-- Modal content -->
    <span class="close">&times;</span>
    <img class="modallifeofpi" src="./images/lifeofpi.jpg" />
    <h1 class="modalheader">Life of pi</h1>
    <h2 class="modalheadertext">Published:</h2>
  </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

Positioning Images with CSS Backgrounds

I am looking to create a fluid background that stretches widthwise, while adjusting its height based on the content. If the content is smaller, I want the background to be truncated. However, if there is a lot of information, I would like the background to ...

Equal height elements - Bootstrap

Is there a way to make all elements in a list the same height, even if one element has more text than the others? I've been using divs for this purpose, but I'm open to switching to li items. Any advice on the best approach? I'm currently w ...

Change the body selector in CssResource to apply custom styles

I have implemented a CssResource within a ClientBundle following the guidelines provided in the documentation at this link. To access the styles from my UiBinder xml, I have used ui:with as explained in the documentation available at this guide. While th ...

Is there a way to retrieve the current form id within the AjaxForm method?

$('form').ajaxForm ({ beforeSend: function() { // To access the current form ID within this function, you can use $(this).attr('id') }, uploadProgress: function(event, position, total, percentComplete) { // codes }, success: function ...

Can you provide the Angular JS alternative for executing a POST request similar to this Curl command?

Trying to translate a Curl command into Angular JS code has been a challenge for me as a newcomer to AngularJS. This specific instance involves a mobile app built on the ionic framework, which utilizes Angular JS. The original curl command looks like this ...

Creating a Mongoose schema to store an array of objects, where updates will automatically add new objects

const mongoose = require('mongoose'); module.exports = mongoose.model('GridModel', { Request_Id : { type : Number, required : true }, viewStudents : { type : Array , default : [] } }); The mongoose model above needs to b ...

Is there a way for a DOMWindow popup to automatically resize to fit its

Currently exploring JQuery and learning on the fly, I'm wondering if there's a method to automatically adjust the size of a DOM window based on its content? I've successfully modified the parameters to accept % width and height instead of p ...

Ensure that both the top row and leftmost column are fixed in a vertical header using JQuery DataTable

Check out the implementation of vertical header flow in Datatables by visiting: https://jsfiddle.net/2unr54zc/ While I have successfully fixed the columns on horizontal scroll, I'm facing difficulty in fixing the first two rows when vertically scroll ...

The Unexpected Mishaps of CSS Grid Layout

I attempted to create a grid using CSS, but I seem to have made an error somewhere in my code. Can someone please take a look at my jsFiddle link and provide some guidance? jsFiddle /*Grid*/ .container { width: 100%; max-width: 1200px; } .row:before, ...

Query Selector(jQuery selector) is a powerful tool for

Here is the HTML Table structure: <table class="display" style="width: 1000px;" id="failoverServers"> <thead> <tr> <th class="row_selector_head"> <input type='checkbox' class='select_all_ch ...

How can you continuously calculate and show the total quantity of items in a list?

Currently, I have lists set up in my sidebar and I'm looking to include a label displaying the number of items within each list. To provide a better understanding of what I'm aiming for, I've put together a JSFiddle demonstration at the fol ...

Organizing an array in JavaScript that includes both version numbers and letters, with each letter representing a specific numerical value

If given an array similar to this one: input = [ "1.1", "1.c", "1.b", "1", "D", "b", "4", "2.1.2", "5.1", "3", & ...

CSS fixed dynamically with JavaScript and multiple div elements placed randomly

Is it possible to dynamically change the position of multiple div elements on a webpage without reloading? I am looking for a way to modify the top and left positions of several divs, all with the same class, simultaneously. I want each div to have a diff ...

Declare React component as a variable

I'm facing a simple issue that I need to solve. After creating a React app using npx create-react-app, I designed a Map component which I integrated into my view with the following code: class App extends Component { render() { return ( ...

Arranging Check Boxes Side by Side

I am struggling to properly align the three checkboxes and tables next to each other. I have managed to get the checkboxes on the same row, but aligning them neatly has proven to be a challenge. Using Notepad++ as my development tool, I am facing formattin ...

Black-colored backdrop for Mui modal

Currently working with a mui modal and encountering an issue where the backdrop appears as solid black, despite setting it to be transparent. I attempted to adjust the color to transparent, but the issue persists. ...

What is the best way to position an image in the bottom right corner of a fluid div container?

I am struggling to position this icon image at the bottom right hand corner of this div, so that it appears as if the message is originating from the icon's head. Despite my efforts, I have yet to find a definitive solution. https://i.stack.imgur.com ...

Employing Modernizer.js to automatically redirect users to a compatible page if drag and drop functionality is not supported

I recently set up modernizer.js to check if a page supports drag and drop functionality. Initially, I had it set up so that one div would display if drag and drop was supported, and another div would show if it wasn't. However, I ran into issues with ...

What is the best way to combine PHP and HTML within a JavaScript script?

I'm facing a challenge with integrating dynamically added elements and a populated drop down on my form. Is there a way to combine the two seamlessly? Below is the code snippet I'm using for dynamically adding and removing elements: $(docu ...

Error Handling in PHP Form with HTML and Image Upload

Let me give you some context first. Recently, I've delved into the world of php and have been at it for a few days now. My code might be a bit messy, but I've done my best to markup as much as possible. I have a form where three things are expec ...