Home > Web Front-end > CSS Tutorial > How to Animate a Div from a Fixed Height to Its Auto Height in jQuery?

How to Animate a Div from a Fixed Height to Its Auto Height in jQuery?

Patricia Arquette
Release: 2024-12-06 14:19:12
Original
378 people have browsed it

How to Animate a Div from a Fixed Height to Its Auto Height in jQuery?

How to Animate an Element to Its Auto Height in jQuery

When attempting to animate a

from a fixed height to its auto height using jQuery, some users may encounter difficulties. Here's a solution to this challenge:

The provided code:

$("div:first").click(function(){
  $("#first").animate({
    height: "auto"
  }, 1000 );
});
Copy after login

encounters issues because browsers will not animate a change in height from a fixed value to "auto."

To achieve the desired animation, follow these steps:

  1. Save the current height:
var curHeight = $('#first').height();
Copy after login
  1. Set the height to "auto" temporarily:
$('#first').css('height', 'auto');
Copy after login
  1. Get the auto height:
var autoHeight = $('#first').height();
Copy after login
  1. Restore the current height and animate to the auto height:
$('#first').height(curHeight).animate({height: autoHeight}, 1000);
Copy after login

This solution works because it first retrieves the current height, allowing the browser to determine its final height when set to "auto."

The above is the detailed content of How to Animate a Div from a Fixed Height to Its Auto Height in jQuery?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template