Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expanding DIV with jQuery

Tags:

html

jquery

css

I have this little bit of code which can be seen in action here

http://jsfiddle.net/rullingen/GCXsq/1/

Which basically expands a div height when hovered over and contracts when not. At the moment it expands from 75px to 300px. I would like to change this so that it expands from 75px to a height that fits the content inside the DIV. I have tried setting the expand value to 'auto' but this does not seem to work well. Can anybody give me a pointer?

HTML

<div class="expand">
    <img src="http://rauanklassnikringing.com/wp-content/uploads/2010/11/carrot-imperator.jpg" alt="" />
</div>
<div class="expand">
    <img src="http://rauanklassnikringing.com/wp-content/uploads/2010/11/carrot-imperator.jpg" alt="" />
</div>

<div class="expand">
    <img src="http://rauanklassnikringing.com/wp-content/uploads/2010/11/carrot-imperator.jpg" alt="" />
</div>

<div class="expand">
    <img src="http://rauanklassnikringing.com/wp-content/uploads/2010/11/carrot-imperator.jpg" alt="" />
</div>

<div class="expand">
    <img src="http://rauanklassnikringing.com/wp-content/uploads/2010/11/carrot-imperator.jpg" alt="" />
</div>

Javascript

$('.expand').hover(function() {
    $(this).animate({
        height: '300px'
    }, 300);
},function() {
    $(this).animate({
        height: '75px'
    }, 300);
});

CSS

.expand {
    overflow: hidden;
    margin-bottom: 15px;
    height: 75px;
}
like image 560
Alex Sadler Avatar asked Feb 16 '11 09:02

Alex Sadler


1 Answers

You can compute the cumulative height of the elements in your <div> and use the result as the argument to animate():

$('.expand').hover(function() {
    var contentHeight = 0;
    $(this).children().each(function() {
        contentHeight += $(this).height();
    });
    $(this).animate({
        height: contentHeight
    }, 300);
}, function() {
    $(this).animate({
        height: '75px'
    }, 300);
});

Updated fiddle here.

like image 131
Frédéric Hamidi Avatar answered Nov 10 '22 01:11

Frédéric Hamidi