Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do i animate a specific height to 100% in jquery

Tags:

jquery

css

height

i want to have a little "preview" of the content in the div, so i made it so small that only only the first line is shown. now i want to animate it that when you click the title, the div will have the height of 100%, but when i use animate(height:"100%") there is no nice sliding.

<a href="javascript:void(0);" class="show_it">title:</a>
<div>
    content<br>
    content_hidden
</div>

<script>
$('.show_it').click(function() {
  $(this).next("div").animate({
    height: 'auto'
  }, 1000, function() {
  });
});
</script>

<style>
div{
    height:20px;
    overflow:hidden;
}
</style>
like image 433
JonasT Avatar asked Jul 29 '11 18:07

JonasT


People also ask

How do you animate height to auto in jQuery?

Here's the code: $("div:first"). click(function(){ $("#first"). animate({ height: "auto" }, 1000 ); });

How do you animate in jQuery?

jQuery Animations - The animate() Method The jQuery animate() method is used to create custom animations. Syntax: $(selector). animate({params},speed,callback);

Is jQuery good for animation?

The jQuery library provides several techniques for adding animation to a web page. These include simple, standard animations that are frequently used, and the ability to craft sophisticated custom effects.

Which method is available in jQuery for animation?

The animate() method performs a custom animation of a set of CSS properties. This method changes an element from one state to another with CSS styles. The CSS property value is changed gradually, to create an animated effect.


2 Answers

Although I am sure there is a better way of doing this as this method is sloppy AT BEST, if you don't find another solution you could always try this:

$('.show_it').click(function() {

// Animate to 100% in 1 millisecond
$(this).parent().next("div").animate({height: 'auto'}, 1);

// Record the height of the div
var newHeight = $(this).parent().next("div").height();

// Animate height to 0% in 1 millisecond
$(this).parent().next("div").animate({height: '0px'}, 1);

// Do the animation using the new fixed height.
  $(this).parent().next("div").animate({
    height: newHeight,
  }, 1000, function() {
  });
});

However, as I said this is very sloppy - if it fits your needs, try jquery slideDown(); this is a much better way to do it.

like image 59
Akoben Avatar answered Sep 22 '22 12:09

Akoben


Or this:

$('.show_it').click(function(){
   $(this).parent().next("div").css("height", "100%");
   var h = $(this).parent().next("div").height();
   $(this).parent().next("div").css("height", "0px");
   $(this).parent().next("div").animate({height: h}, 1000, function() {
   });
});
like image 45
justincohler Avatar answered Sep 22 '22 12:09

justincohler