jQuery: Display Image Popup on Click of Thumbnail

If you want to display a larger version of an image when a user clicks on a thumbnail, jQuery can do this easily. Here's how:

├Źndice
  1. 1. Create HTML Markup
  2. 2. Hide the Popup Image
  3. 3. Write the jQuery
  4. 4. Style the Popup Image
  5. Conclusion

1. Create HTML Markup

First, create the HTML markup for the thumbnail and popup image. The thumbnail should be an <img> tag with a class or data attribute to identify it. The popup image should be an <img> tag with the larger image source and a unique ID.

<img src="thumbnail.jpg" alt="Thumbnail" class="thumbnail">
<img src="fullsize.jpg" alt="Full Size Image" id="popup-image">

2. Hide the Popup Image

You'll want to initially hide the popup image using CSS:

<style>
  #popup-image {
    display: none;
  }
</style>

3. Write the jQuery

Now, you can write the jQuery to handle the click event on the thumbnail and display the popup image. Here's an example:

<script>
  $(document).ready(function() {
    $('.thumbnail').click(function() {
      $('#popup-image').fadeIn();
    });

    $('#popup-image').click(function() {
      $(this).fadeOut();
    });
  });
</script>

This code waits for the document to load, then adds a click event listener to all elements with the .thumbnail class. When a thumbnail is clicked, the code fades in the popup image. The code also adds a click event listener to the popup image itself, so that when it is clicked, it fades out.

4. Style the Popup Image

You may want to add some additional CSS to style the popup image, such as positioning it in the center of the screen. Here's an example:

<style>
  #popup-image {
    display: none;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 9999;
  }
</style>

This CSS centers the image on the screen using the position: fixed property and the transform: translate(-50%, -50%) property.

Conclusion

With just a few lines of jQuery and CSS, you can create a simple image popup that displays a larger version of an image when a user clicks on a thumbnail.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information