Extending DIV with jQuery

I have some code that can be seen in action here

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

Which basically expands the height of the div when it hangs and contracts when not. Currently it is expanding from 75px to 300px. I would like to change this so that it expands from 75 pixels to a height that matches the content inside the DIV. I tried to set the extension value to "auto", but this does not work well. Can someone 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;
}
+5
source share
2 answers

You can calculate the cumulative height of the elements in <div>and use the result as an argument 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);
});

.

+9

": " . IE8. IE7 -  (zoom: 1; * display: inline; _height: 30px; ") - .

0

All Articles