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

Employing CSS animations to elevate div elements

Currently, I am working on animating a table of divs and trying to achieve an effect where a new div enters and "bumps up" the existing ones. In my current setup, Message i3 is overlapping Message 2 instead of bumping it up. How can I make Messages 1 and 2 ...

javascript hide rows without data

I have a knack for tweaking existing code to suit my needs, but I'm not very proficient in writing my own from scratch. That being said, here's my current dilemma. My pool league uses a Google sheet to manage a variety of statistics, and with so ...

Proper application of article, aside, and header elements

Can someone help me with my page template setup? I have a sidebar on the left and main content area on the right. I'm wondering if I am using the article, aside, and header tags correctly. Also, should I attach classes/ids to html5 elements or is that ...

Modifying a div element upon the successful completion of an ajax/json request

Currently, I have a form on my webpage for creating a new album. Alongside this form, there is also a delete album form. After successfully creating an album, I want to automatically update the checkbox list in the delete album form with the details of the ...

Tips on getting the bot to react to a single "event" mentioned in the sentence, without multiple occurrences

Things are a bit complicated, but here's an example to illustrate: I've set up this event: client.on('message', async message => { if (message.content.toLowerCase().includes("megumin")) { message.channel.send("W ...

Is there a way to set the starting position of the overflow scroll to the middle?

Is there a way to have the overflow-x scrollbar scroll position start in the middle rather than on the left side? Currently, it always begins at the left side. Here is what it looks like now: https://i.stack.imgur.com/NN5Ty.png If anyone knows of a soluti ...

What is the best way to search for items using only a portion of a phone number or typing a name in any case (uppercase, lowercase) and still get accurate results?

let contacts = [ { name: 'John', phone: 987654 }, { name: 'Sara', phone: 654321 } ] I am developing a contact manager app with various functions to manage contacts. Add new contac ...

The onClick event's detail property is persisting even after the React component has been replaced

In the onClick event, the value of event.detail indicates the number of clicks, with a double-click having event.detail = 2. It seems that when the React component being clicked is replaced, the event.detail value does not reset. This could be due to Reac ...

External CSS file unable to load background image as referenced

I am facing an issue with this code in my external CSS file as it doesn't seem to work at all. Strangely, when I move it internally, everything functions perfectly. Any thoughts on what could be causing this discrepancy? html { background-image:url(i ...

What causes the error "searchInput" to be undefined?

Currently, I am facing an issue while attempting to search for individuals stored in an array within the Redux store. Whenever I try to execute a search, an error is triggered with the following message: Cannot read property 'searchInput' of und ...

Limiting ng-repeat in AngularJS when the last item on the object is reached

I have a large object being repeated using ng-repeat, and it runs smoothly on Chrome and Opera. However, when it comes to browsers like Mozilla and IE, the performance is very slow. I tried implementing pagination, which helped speed things up, but ideally ...

Only trigger the function for a single bootstrap modal out of three on the current page

I'm facing a challenge on a page where I have 3 bootstrap modals and I need to trigger a function only for one modal while excluding the other two. $("body").on("shown.bs.modal", function() { alert('modal Open'); //this alert should ...

Changing the 'checked' attribute does not have any impact on how it appears in the browser

I am working on a button group where each button should light up when it is selected. The functionality is not fully working as expected; only one button should be active at a time. let stanceBar = ["long", "short", "out", "none"] .map( ...

Update the value in a nested object array by cross-referencing it with a second nested object array and inserting the object into the specified

I have a large array of objects with over 10,000 records. Each object contains an array in a specific key value, which needs to be iterated and compared with another array of objects. If there is a match, I want to replace that value with the corresponding ...

Exploring Angular 10: Managing Two Promises in ngOnInit

I am currently working on integrating the Strava API into my Angular app. To summarize briefly: When a user clicks on a button to connect to Strava They are redirected to Strava for authentication (using PKCE) Strava then redirects back to my app with a ...

Issue with Angular Factory not being invoked

I am currently using a tutorial to create a MEAN app with Google Maps. However, I have encountered an issue where the map is not appearing on the page. Surprisingly, there are no errors in the browser console and even when debugging with node-inspector, I ...

php script within a literal .tpl file

Is there a way to perform a json_encode within a literal javascript block in the context of a Smarty template? {literal} <script> function openWin() { var O = {php} echo json_encode($obj);{/php}; // syntax error ...

Emphasize table cells dynamically

Query How can I dynamically highlight a selected td? Codepen Example View Pen here Code Snippet The map consists of a randomly generated 2D array, like this: map = [[1,1,1,1,0], [1,0,0,0,0], [1,0,1,1,1], [1,0,0,0,1], [1,1, ...

Is there a way to incorporate an MTN Momo or Orange Money payment system into your application if you are not a registered business entity?

Implementing an MTN Momo and Orange Money payment system through their respective APIs is crucial. In addition, I am seeking a dependable and effective method to seamlessly integrate these diverse APIs. During my attempt to incorporate the API via their ...

Retrieve data from a MySQL table based on a specific condition in PHP

Can someone assist me with fetching data from a table where the valid_from date is less than a specified date (excluding the current date)? I have a table that looks like this: view my table here For instance, if my date is 02-04-2015, I would want to re ...