Modify the height using JavaScript and then revert back to the initial CSS height

Looking for assistance with a JavaScript issue that I'm currently facing.

Q1: Javascript Function to Return Image Height and Margin

My website layout consists of a horizontal scroll of smaller images arranged in a grid, each with different height percentages and margins for positioning. When an image is clicked, it expands to height:100% and margin:0, clearing all previous styles to create a simple large image layout.

My query is, how can I implement a function that returns the height and margins to their original CSS settings when clicking on .image-container?

JS Fiddle Demo (click any center image)

// GALLERY 100% height
    $('.image-container').click(function(){
        $('.image-container img').animate({'height': '100%'},900) 
        .animate({'margin': '0'},900); 

    });

    // ? REMOVE HEIGHT ? 
    $('.image-container').click(function(){
        $('.image-container img').animate({'height': '?'},900)
        .animate({'margin': '?'},900); 

    });

EDIT UPDATED QUESTION: Q2 HOW TO MAKE PAGE SIZE GROW WITH LARGER IMAGES

Currently, my .image-container is set to a large width. However, with responsive images, it's challenging to determine the correct width. Is there a way to dynamically adjust the width to accommodate larger images when clicked (as shown above)?

.image-container {
display:block;
width:3600px;
height: 75%;
float:left;

position:absolute;
top: 13%;
left: 120px;

z-index: -1;

Thank you for any assistance!

Answer №1

To keep track of the initial height, it is important to save it in a variable.

Take a look at the revised fiddle

var storedHeight;
        // Adjusting gallery height to 100%
        $('.image-container').click(function(){
            storedHeight = $('.image-container img').height();
            $('.image-container img').animate({'height': '100%'},900) 
            .animate({'margin': '0'},900); 

        });

        //Resetting height
        $('.image-container').click(function(){
            $('.image-container img').animate({'height': storedHeight},900)
            .animate({'margin': '0'},900); 

        });

UPDATE:

Apologies for the error in the prior solution. I mistakenly used the click function twice unnecessarily. Here is the corrected solution along with the revised fiddle.

       var storedHeight;
       $('.image-container').click(function () {
           if (!storedHeight) storedHeight = $('.image-container img').height();
           if ($('.image-container img').css('height') == storedHeight + "px") { // Adjusting gallery height to 100%
               $('.image-container img').animate({
                   'height': '100%'
               }, 900).animate({
                   'margin': '0'
               }, 900);
           } else { //Resetting height
               $('.image-container img').animate({
                   'height': storedHeight
               }, 900).animate({
                   'margin': '0'
               }, 900);
           }
       });

Answer №2

My plan is to try the following approach:

// Initial setup
    var heights = new Array();
    var margins = new Array();
    $('.image-container img').each(function(){
       heights.push($(this).css('height'));
    });
    $('.image-container img').each(function(){
       margins.push($(this).css('margin'));
    });
// 
    $('.image-container').click(function(){
        $('.image-container img').animate({'height': '100%'},900)
        .animate({'margin': '0'},900); 

    });

    // Change back to original height and margin
    $('.image-container').click(function(){
        $('.image-container img').animate({'height': heights[$(this).index()]},900)
        .animate({'margin': margins[$(this).index()]},900); 

    });

Answer №3

If you want to revert changes made with a 'click' event, it's recommended to use the focusout and blur events instead. This way, you can avoid overriding the initial click implementation. A better approach would be to resize the image when clicked and restore its original size when clicked outside.

Here's an example:

// GALLERY 100% height
$('.image-container')
  .bind('click', function(){
    $('.image-container img').animate({height: '100%'}, 900) 
    .animate({margin: 0}, 900);
  })
  .bind('focusout blur', function(){
    $('.image-container img').animate({height: ''}, 900) 
    .animate({margin: ''}, 900);
  });

Alternatively, you can use classes to define different behaviors for clicking and clicking again, like this:

<style>
.clickimage { height : 100%; margin :0;}
.yourOriginalValues {height : original; margin : original;}
</style>

$('.yourOriginalValues').click(function(){
  $(this).switchClass("yourOriginalValues", "clickimage", 900);
});
$('.clickimage).click(function(){
  $(this).switchClass("clickimage", "yourOriginalValues", 900);
});      

ps. The switchClass method is a jQuery UI functionality.

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

The issue of execution order in JavaScript Recursion with promises

In the process of developing a method for creating markup to be used in a web app's off-canvas navigation. One of the challenges I am facing is making an asynchronous callback to another service that provides children nodes for the parent menu node (r ...

Navigating the rollout of a fresh new design

When implementing a new design on a website, how can you bypass the need for users to clear their browser cache in order to see the updated changes? Is there a way to automatically refresh the cache once a new version of the website is uploaded, or are th ...

What is the best way to detect a specific button press from an external component?

I need to integrate an external component written in Vue.js that contains multiple buttons. How can I specifically target and capture the click event of a particular button called firstButtonClick() within this external component? Here is how the External ...

designing a button layout with bootstrap framework

I am attempting to position a "Redigera" button after the "Avsluta" button <div class="row"> <div class="col-md-4"> </div> <div class="col-md-4"></div> <div class="col-md-4"> <button class=" ...

Move the accordion slider to the top of the browser

I'm working with an accordion menu that has some long content. To make it more user-friendly, I want to add a slide effect when the accordion items are opened. Right now, if you open the first two menu items, the last item's content is cut off a ...

Analyze the information presented in an HTML table and determine the correct response in a Q&A quiz application

I need to compare each row with a specific row and highlight the border accordingly: <table *ngFor="let Question from Questions| paginate: { itemsPerPage: 1, currentPage: p }"> <tr><td>emp.question</td></tr> <tr> ...

Issue with Bootstrap spinner not functioning properly within a table featuring a sticky header

In the Razor Page app I'm working on, the index page features a table with a sticky header and a spinner in one of the columns. However, when the table is scrolled vertically, the text in the column goes under the sticky header, while the spinner rema ...

Can you identify the animation being used on this button - is it CSS or JavaScript?

While browsing ThemeForest, I stumbled upon this theme: What caught my eye were the animation effects on the two buttons in the slider ("buy intense now" and "start a journey"). I tried to inspect the code using Firebug but couldn't figure it out com ...

Leverage the values of object properties from a pair of JavaScript arrays containing objects

I am working with two arrays let arr1 = [{'id': 'ee', 'seat': '12'}, {'id': 'aa', 'seat': '8'} ] let arr2 = [ {'id': 's22', 'num': '&ap ...

The appearance of the logout button may differ depending on the web browser being used

I have implemented a straightforward logout button using the following code: <li><a href="http://localhost:8666/web1/profile/mainpage/logout.php" onclick="return confirm('Are you sure to logout?');">Log Out</a>&l ...

floating point for a list item compared to other elements

nav > ul > li { float: left; } #one { float: left; } <nav> <ul> <li> he has a cow </li> <li > he has a dog </li> <li> he has a mouse </li> </ul> & ...

Displaying Vue v-for data in console.log

One interesting issue arises when printing a list in HTML and checking the output in HTML versus in console.log. It seems that the output is duplicated in the console. After some investigation, I made the following observations: Not showing the product ...

Tips for modifying the language of an Angular Application's OneTrust Cookie Banner

I'm currently developing an Angular application and utilizing OneTrust for managing cookie consent. The issue I'm encountering is that while the rest of the components on the login page are properly translated into the target language, the OneTru ...

Inserting a picture using CSS

I attempted to include an image in a footer div, but I have not been successful with the following approach: Here is the HTML code I tried: <footer> <div class="imagenFooter" style="background-image: url(&quot;./images/footer-bg.jpg&quo ...

Guide to retrieving IDs of images on a canvas during drag and drop functionality

I've developed a finite state machine drawing tool that includes drag-and-drop functionality for different images, such as states and arrows. Each arrow creates a div tag for the transition, with unique ids assigned to every state, arrow, and transiti ...

Error thrown due to syntax issues in react.d.ts declaration file in TypeScript

Currently, I am attempting to integrate react with typescript in my project. However, typescript is generating syntax errors for the react.d.ts file sourced from Github: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/react The encountered ...

What is the best way to retrieve all the keys from an array?

I am looking to retrieve the address, latitude, and longitude data dynamically: let Orders= [{ pedido: this.listAddress[0].address, lat: this.listAddress[0].lat, lng: this.listAddress[0].lng }] The above code only fetches the first item from the lis ...

Trigger a click based on the CSS path starting from a specific element in the DOM

I am currently developing a feature for mouse activities, such as moving the mouse, clicking, and scrolling. I want to be able to record these activities and then playback them later on. So far, I have successfully recorded mouse movement, and now I need t ...

What is the best way to apply changes to every class in JavaScript?

Check out this HTML and CSS code sample! body{ font-family: Verdana, Geneva, sans-serif; } .box{ width: 140px; height: 140px; background-color: red; display: none; position:relative; margin-left: auto; margin-right: auto; } .bold{ font ...

Retrieve a photo from a website address and determine its dimensions

When grabbing an image from a URL using this function: const fetch = require("node-fetch"); function getImageFromUrl(url) { return fetch(url).then((response) => response.blob()); } To determine the dimensions of the images, I am utilizing ...