What is the best way to make an image expand when clicked, align it in the center of the webpage, and have it return to its original position with just one more click by utilizing

Currently, this is the code I am working with. The JavaScript functionality is working well, however, there seems to be an issue where the image does not return to its original size on a second click. Additionally, I am having trouble getting the CSS to center the image.

function enlargeImg(img) {
    img.style.transform = "scale(1.5)";
    img.style.transition =
        "transform 0.25s ease";
}
img {
    position: relative;
    margin-left: auto;
    margin-right: auto;
    width: 100%;
}
 <div class="container">
        <div class="heading">
            <h3>Photo <span>Gallery</span></h3>
        </div>
        <div class="box">

            <div class="dream">

                <img src="./tucson/DSC03046.JPG" onclick="enlargeImg(this)">
                <img src="./tucsonBW/nutsNBoltsBW.jpg">
                <img src="./nature/deadTree.JPEG">
                <img src="./nature/honeyBee.JPG">
                <img src="./tucsonBW/mailBoxBW.jpg">

            </div>

Answer №1

If you want to ensure that the image returns to its original size when a different image is clicked, you can manage this by tracking the currently enlarged image and resetting its size before enlarging the new one.

let currentImageId;

function enlargeImage(imageId) {
  let image = document.getElementById(imageId);

  // Reset size of previously enlarged image, if there is any
  if (currentImageId) {
    let currentImage = document.getElementById(currentImageId);
    currentImage.classList.remove("enlarged");
  }

  // Enlarge the clicked image
  image.classList.add("enlarged");

  // Set the current image id to the clicked image id
  currentImageId = imageId;
}
img {
  position: relative;
  margin-left: auto;
  margin-right: auto;
  width: 40px;
  height: 40px;
}

.enlarged {
  transform: scale(1.5);
  transition: transform 1s ease;
  position: absolute;
  width: 80px;
  height: 80px;
  margin: auto;
  left: 300px;
}
<div class="container">
  <div class="heading">
    <h3>Photo <span>Gallery</span></h3>
  </div>
  <div class="box">
    <div class="dream">
      <img id="img1" src="https://www.w3schools.com/w3css/img_avatar1.png" onclick="enlargeImage(this.id)" />
      <img id="img2" src="https://www.w3schools.com/w3css/img_avatar2.png" onclick="enlargeImage(this.id)" />
      <img id="img3" src="https://www.w3schools.com/w3css/img_avatar3.png" onclick="enlargeImage(this.id)" />
    </div>
  </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

What methods can I employ with JavaScript to catalog data collected from an HTML form?

Currently, my form requires users to input a username that cannot start or end with a period (.). I have implemented some code but I believe there is an issue with the .value[0] parts. //Checking Username if (document.getElementById("uName&quo ...

Adding elements to a global array via a callback function in JavaScript: A step-by-step guide

I am currently working on querying and adding users to a global array from my database. My goal is to store the elements in this global array so that I can access it from any part of my application. app.get("/admin/orders", (req, res) => { Q ...

The 'this' variable is malfunctioning when trying to assign a JSONP array to an AngularJS controller

I'm working with a REST service in my angular controller and using JSONP to make the call. I need to store the array that is returned from the service into a variable. This is what I currently have: this.testTheRest = function() { $http.jsonp(&a ...

Changing a string into a date format with the help of JavaScript AngularJS

My string is as follows: 13-12-2017 05:05 AM I am looking to convert it to the following format: Date 2017-12-13T05:05:00.000Z Attempted Solution: var mydate = '13-12-2017 05:05 AM'; var selectedDate = new Date(mydate); Upon logging the selec ...

Tips for updating property values when calling a TypeScript function

Hello everyone, I am looking to convert a snippet of JavaScript code into TypeScript. JavaScript function newState(name){ var state ={ name : name, age : 0 } return state } function initStates() { this.JamesStat ...

Despite returning an "OK" status, the jQuery Ajax Codebehind Post fails to function properly

Attempting to call a function in ASP.NET with jQuery Ajax: var params = "{'name':" + "\"" + name + "\"}"; $.ajax({ type: "POST", url: "CreateTopic.aspx/CreateNewTopic", data: params, ...

What sets apart element.class from element .class in CSS?

I've been puzzled trying to figure out why my CSS was not applying when I had mydiv .myclass { font-size: 24px !important; } But then I randomly decided to try mydiv.myclass { font-size: 24px !important; } and surprisingly it worked perfectly. Wh ...

The min-height property does not seem to be compatible with -webkit-calc

I've been experimenting with this code: .main{ min-height: -moz-calc(100% -50px); min-height: -webkit-calc(100% -50px); min-height: calc(100% -50px); background-color:#000; color:white; } html{ height:100%; } <html ...

Disappear solely upon clicking on the menu

Currently, I am working on implementing navigation for menu items. The functionality I want to achieve is that when a user hovers over a menu item, it extends, and when they move the mouse away, it retracts. I have been able to make the menu stay in the ex ...

Converting all numbers separated by commas to numbers separated by periods in a string using JavaScript

Imagine a scenario where you have a string containing numbers, such as, test() test 12,01% test (12,4) 12.3 s 2 some other text, other text, 2,text Your task is to replace the numbers with decimals instead of commas without altering anything else in the ...

Having issues with the right margin in HTML5 canvas and struggling to remove the scroll bar

I am struggling with adjusting the margins of my canvas to ensure equal spacing on both sides without any horizontal scroll bars. Desired Outcome: Equal margin on both sides of canvas without any horizontal scroll bars. Issue: The margin-right property i ...

Highlighting syntax on the server side

I have some code blocks that I want to emphasize. Currently, I am using prismjs for this purpose. However, when I try to highlight several code blocks, the page takes more than 5 seconds to load on my somewhat slow PC. Interestingly, if I remove the prism ...

What is the best way to apply absolute positioning to an image tag that is related to

I'm completely new to both rails and javascript. In my app, I have a table of venues categorized by type and area. These venues are displayed as partials on the index page, each with its own icon that appears on a map located to the left of the screen ...

Having trouble making event listeners work with React useState in Next.js?

I'm currently working on a webpage where I want to have a fixed hamburger icon in the top-right corner that, when clicked, opens a navbar. The navbar should close if the user clicks outside of it, and the hamburger icon should reappear. Since Next.js ...

Utilizing the Public Directory in Vite Compilation

One issue I encountered in my project with Vite version 2.9.7 is related to the handling of images stored in the public folder within the project's root directory. To import these images, I utilized Vite's import.meta.glob function, like so: imp ...

What is the method to determine the size of a Map object in Firestore database?

I currently have two elements within a document: an empty array, and a map object containing three components. If the array is empty, it transforms into type array. In this case, I can execute console.log(vehicles.Motorcycles.length) to receive a return of ...

Tips for preventing the parent element's height from fluctuating when displaying a child div using v-if

I have a main container and an inner container. The inner container is displayed using v-if. I want to include a transition effect on the inner element, but after the transition ends, the height of the parent container changes abruptly and looks unattracti ...

Matter of Representing Nested For Loops in Javascript Arrays

When I have two arrays that intersect at certain elements, the resulting function should ideally output A, B, Y. However, in this case, it displays all possible combinations of lista.length * listb.length. <script> window.onload = function(){ ...

Dynamic grid arrangement showcasing cells of varying heights

I am dealing with a grid layout where cells are dynamically generated using the following code: <style> .calWrapper{ width:200px; float:left; } </style> <div class="container"> <?php for($i=1; $i<=12; $i++){ echo ...

Issue with Bootstrap 4 anchor links not leading to intended target

I recently built a one-page index page using Bootstrap 4, complete with a navbar containing hyperlinks that smoothly navigate to different sections of the page. For example, the "Events" nav link takes users to the section identified by id="events&quo ...