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
Patricia ArquetteOriginal
2024-12-06 14:19:12417browse

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 );
});

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();
  1. Set the height to "auto" temporarily:
$('#first').css('height', 'auto');
  1. Get the auto height:
var autoHeight = $('#first').height();
  1. Restore the current height and animate to the auto height:
$('#first').height(curHeight).animate({height: autoHeight}, 1000);

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!

Statement:
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