Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I Animate an Element to its natural height using jQuery
    primarykey
    data
    text
    <p>I'm trying to get an element to animate to its "natural" height - i.e. the height it would be if it had <code>height: auto;</code>.</p> <p>I've come up with this:</p> <pre><code>var currentHeight = $this.height(); $this.css('height', 'auto'); var height = $this.height(); $this.css('height', currentHeight + 'px'); $this.animate({'height': height}); </code></pre> <p>Is there a better way to do this? It feels like a bit of a hack.</p> <p>Edit: Here's a complete script to play with for anyone that wants to test.</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;title&gt;jQuery&lt;/title&gt; &lt;style type="text/css"&gt; p { overflow: hidden; background-color: red; border: 1px solid black; } .closed { height: 1px; } &lt;/style&gt; &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $().ready(function() { $('div').click(function() { $('p').each(function() { var $this = $(this); if ($this.hasClass('closed')) { var currentHeight = $this.height(); $this.css('height', 'auto'); var height = $this.height(); $this.css('height', currentHeight + 'px'); $this.animate({'height': height}); } else { $this.animate({'height': 1}); } $this.toggleClass('closed'); }); }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt;Click Me&lt;/div&gt; &lt;p&gt;Hello - I started open&lt;/p&gt; &lt;p class="closed"&gt;Hello - I started closed&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload