What steps do I need to take to enlarge an image when it is clicked?

I am working on a gallery project and I would like each photo to expand to full screen when clicked, similar to this example:

https://i.sstatic.net/nRWsV.jpg

Currently, my code includes a click handler on each image that adds a class zoom to the clicked image. However, my CSS only enlarges the image without centering it on the entire page as shown in the example. Here is my current code snippet:

.gallery img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  align-content: center;
  object-position: center;
  transition: transform ease-in-out 0.5s;
}

.zoom {
  z-index: 1;
  transform: scale(1.5);
  display: block;
  margin-left: auto;
  margin-right: auto;
}
<body onload="getPics()">
    <div class="container">
      <h1>Photo Gallery</h1>
      <div class="gallery">
        <img
          src="https://images.unsplash.com/photo-1543517515-d6ff15a98642?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjQ0NDc3fQ&s=493802e93ec426171750ac2291e2867e"
        /><img
          src="https://images.unsplash.com/photo-1543517515-d6ff15a98642?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjQ0NDc3fQ&s=493802e93ec426171750ac2291e2867e"
        /><img
          src="https://images.unsplash.com/photo-1543517515-d6ff15a98642?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjQ0NDc3fQ&s=493802e93ec426171750ac2291e2867e"
        />
      </div>
    </div>
  </body>

How can I modify the zoom CSS to make the image go into full-screen mode?

Answer №1

Working with zoom can be a challenge - determining calculations based on the current viewport dimensions and repositioning the image is necessary.

Alternatively, you can have an element that covers the entire viewport with a high z-index but remains hidden by default. When a user clicks on an image, it becomes the background of this large element, ensuring it fits perfectly using background-size contain.

In this code snippet, clicking on the enlarged image removes it from view.

function getPics() {} //only for demo purposes
const imgs = document.querySelectorAll('.gallery img');
const fullPage = document.querySelector('#fullpage');

imgs.forEach(img => {
  img.addEventListener('click', function() {
    fullPage.style.backgroundImage = 'url(' + img.src + ')';
    fullPage.style.display = 'block';
  });
});
#fullpage {
  display: none;
  position: absolute;
  z-index: 9999;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-size: contain;
  background-repeat: no-repeat no-repeat;
  background-position: center center;
  background-color: black;
}
<body onload="getPics()">
  <div class="container">
    <h1>Photo Gallery</h1>
    <div class="gallery">
      <img src="https://images.unsplash.com/photo-1543517515-d6ff15a98642?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjQ0NDc3fQ&s=493802e93ec426171750ac2291e2867e" /><img src="https://images.unsplash.com/photo-1543517515-d6ff15a98642?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjQ0NDc3fQ&s=493802e93ec426171750ac2291e2867e"
      /><img src="https://images.unsplash.com/photo-1543517515-d6ff15a98642?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjQ0NDc3fQ&s=493802e93ec426171750ac2291e2867e" />
    </div>
  </div>
  <div id="fullpage" onclick="this.style.display='none';"></div>

Answer №2

Check out this simple jQuery code that allows users to click on any image and view it fullscreen:

$(document).ready(function(){$("img").click(function(){this.requestFullscreen()})});

Answer №3

All images in the document can be manipulated using the same class.

        $("image tag").click(function(){

Firstly, display the container we are working with.

Apply CSS to hide everything except the specified container.

Add an image section inside the hidden container and style it using jQuery .css(); method.

            $("#Hidden Container").fadeIn(200);
            $("html").css("overflow","hidden");
            $(".image_section").css("background","url("+$(this).attr('src')+")");
        })

An exit icon is displayed on the corner for exiting full screen using .fadeOut(); method

        $(".fa_cancel_icon").click(function(){
            $("#full_page").fadeOut(200);
            $("html").css("overflow","auto")
        })

CSS properties for the Hidden Container should include:

        height: 100vh!important;
        width: 100vw;
        background-color: black;
        display: none;
        z-index: 1000;
        position: fixed;
        top: 0;
        right: 0;
        left: 0;
        bottom: 0;

For the Image Section, use the following CSS. Add !important if necessary:

        height: 100%;
        width: 75%;
        z-index: 9999;
        margin: 0 auto;
        background-size: cover;
        background-position: center;
        background-repeat: no-repeat;

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

React snap scrolling feature is not working as intended

I've been attempting to implement the snap scroll feature in my react app, but I'm facing issues with it. The regular CSS method doesn't seem to work well in Chrome, as discussed in this Scroll Snap Skips Section on Smaller Screen - Chrome t ...

Develop a responsive image component with flexible dimensions in React

I am currently working on developing a dynamic image component that utilizes the material-ui CardMedia and is configured to accept specific height and width parameters. The code snippet I have is as follows: interface ImageDim extends StyledProps { wid ...

What are some helpful tools for organizing data from an External API in NodeJS and Express?

One of the tasks I'm currently working on involves connecting to an external API through my backend system. Data flow : External API -> My backend -> Client side Typically, I would use modules such as request or http to facilitate this p ...

What could be causing my for loop to not function properly within the ngOnInit lifecycle hook?

I am attempting to create a nested loop structure in order to access an array that is inside an object within an array of objects, and then store this data into a new array. My issue arises as the first loop executes successfully but the second one does no ...

Unable to capture user input text using $watch in AngularJS when applied on ng-if condition

I have developed a cross-platform application using AngularJS, Monaca, and OnsenUI. In my login view, I check if the user has previously logged in by querying a SQLite database. Depending on whether there is data in the database, I either display a welcom ...

Using MySQL with asynchronous promises

I'm currently delving into the world of promises. Here is a snippet of my code: checkEmailUsername = function(email, username) { return new Promise(function(resolve, reject) { var query; query = "SELECT * FROM users WHERE email = ? O ...

Guide to creating unit tests for document.URL in Angular 5 specifications

Currently attempting to simulate document.URL = 'dashboard'; however, encountering an issue where it states that I can't assign to url because its readonly property. This problem arose while writing jasmine test cases click here for image de ...

What steps should be taken to validate an HTML5 form without actually submitting it?

I am working on a form that includes various HTML attributes such as: <form> <label>Full Name</label> <input type="text" name="firstname" class="span3" required="required"> <label>Email Address</label&g ...

What's causing the misalignment in the top row?

What could be causing the misalignment of cells in the first row? JSfiddle link Here is the code snippet: .box3 { margin: auto; width: auto; height: 300px; } .tb2 { border-collapse: collapse; color: black; text-align: center; ma ...

Navigate to the subsequent field in an HTML5 form without any manual intervention

I have created the following HTML5 form: <form> <input type="text" name="orderno" /> <input name="picture" id="img" type="file" accept="image/*" capture="camera" /> <input class="btn-success" type="submit" name="submit" value="Uplo ...

Converting a JSON object to a URL for SliderBox in React Native

I am encountering an issue when passing a URL to SliderBox as props. It functions properly if I pass the image using state or an object in the component file or at the rendered screen. The URL is obtained from a JSON object. Here is how I utilized SliderBo ...

glitch in three.js game movement mechanics

After spending some time fine-tuning the camera movement in my three.js project, I am now ready to introduce movement. Initially, I attempted to use camera.translateZ(movementSpeed), but this caused the camera to fly, and I want to constrain the movement t ...

Is it possible to submit a form using both ajax and normal POST simultaneously?

I have a form that submits data to an external URL and at the same time I want to save it in my database. I attempted using Ajax to submit and then try to submit a normal POST request in the Ajax success function. Here is my code: <form action="http:/ ...

The Number.toLocaleString function does not work properly in the pt-BR locale when tested in

A function named toCurrency has been created for converting strings or numbers to locale-specific formats: function toCurrency( value: string | number, locale: string = "en-US", currency: string = "USD", options?: Intl.N ...

Issue with box shadow appearing incorrectly as element content increases in size while the body has an image background

After applying a box shadow to the header div, I noticed that the box shadow doesn't display properly when the hidden elements within the header are revealed. <div id="header"> <div id="logo"> <a href="#"><img src="logo.png" ...

Guide to resolving the issue of "Links lacking a clear name" in Lighthouse

Lighthouse is recommending that I address my a href text Here is the HTML code snippet in question: <a href="https://twitter.com/@some-name-here" target="_blank" rel="noopener" class="social-icon twitter grayscale"></a> The issue is that I a ...

naming variables flexibly in javascript

Is there a more efficient way to condense this code into a loop and dynamically name the variables? this works var aMainNav = ['b1', 'b2', 'b3']; aMainNav[0] = $('.mainNav li:nth-child(1)'); aMainNav[1] = $(&apo ...

Scrolling the page with JavaScript

Is it possible for my webpage to smoothly scroll to a specific div within the page using JavaScript? I know I can get the offset dimensions of the target div and then use scrollTop to navigate to that area, but is this enough to achieve a smooth scrollin ...

Issues with the styling of C3.js

I'm encountering some issues with a visualization I'm trying to create using C3.js. The top and side edges of my scatter chart are getting cropped (likely due to changing the radius of the bubbles), but I don't believe that should be cau ...

I am encountering an issue with the appendChild() method when trying to create a new element using createElement("ul")

I am facing an issue with creating a UL and LI elements beneath the P tag. Would appreciate it if someone could review my code below. The javascript is showing the following error message: Uncaught TypeError: thisIsQuizContainer.appendChild is not a fu ...