How To Zoom Image On Click In Jquery

In this blog post, we will learn how to zoom an image on click using jQuery. This is a handy feature for users who want to take a closer look at an image on a website, and it’s relatively simple to implement.

Prerequisites

Before we begin, make sure you have the following prerequisites in place:

  • A basic understanding of HTML, CSS, and JavaScript.
  • jQuery library included in your project. You can include it using the following CDN link:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

Step 1: Create the HTML structure

First, we’ll create a simple HTML structure with an image and a container to hold the zoomed image. Add the following HTML code to your web page:

<!-- Image container -->
<div class="image-container">
    <img src="path/to/your/image.jpg" alt="Sample Image" />
</div>

<!-- Zoomed image container -->
<div class="zoom-container"></div>
    

Step 2: Add CSS styles

Next, we’ll add some basic CSS styles to make the image responsive and style the zoomed image container. Add the following CSS code to your web page or external stylesheet:

<style>
.image-container img {
    max-width: 100%;
    height: auto;
}

.zoom-container {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    display: none;
    align-items: center;
    justify-content: center;
}

.zoom-container img {
    max-width: 90%;
    max-height: 90%;
    border: 5px solid #fff;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
}
</style>
    

Step 3: Implement the jQuery functionality

Finally, let’s write the jQuery code to handle the image click event and display the zoomed image. Add the following jQuery code to your web page:

<script>
$(document).ready(function () {
    // Zoom image on click
    $('.image-container img').on('click', function () {
        var imgSrc = $(this).attr('src');
        $('.zoom-container').html('<img src="' + imgSrc + '" alt="Zoomed Image" />').fadeIn();
    });

    // Close zoomed image on click
    $('.zoom-container').on('click', function () {
        $(this).fadeOut();
    });
});
</script>

Conclusion

And that’s it! We’ve successfully implemented a simple image zoom functionality using jQuery. You can now click on the image to view it in a zoomed state and click anywhere outside the zoomed image to close it. Feel free to customize the CSS styles and jQuery code to fit your specific needs.