Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/jQuery animate to dynamic height?

Does anyone know why this animates fine:

function setContainerHeight() {
    $(".pagecontainer").animate({
        height: '700px'
    }, 500);
}

i.e. a fixed height, but this doesn't animate at all?

function setContainerHeight() {
    $(".pagecontainer").animate({
        height: 'auto'
    }, 500);
}

It still resizes to auto, but no animation, just snaps to it.

My code:

JS:

<script>

    function setContainerHeight() {
        $(".pagecontainer").animate({
            height: 'auto'
        }, 500);
    }

    $('.link').on('click', function(e){
        $('.pagecontainer>div').fadeOut(0);
        setContainerHeight();
        $(this.getAttribute("href")).fadeIn();
    });

</script>

CSS:

.pagecontainer {
min-height:450px;
width:80%;
min-width:800px;
padding:50px 0;
margin: 0 auto;
}
.pagecontainer>div{
display: none; /*wait until page needs to be faded in*/
padding-left:50px;
padding-right:50px;
position:relative;
}

HTML:

<div class="pagecontainer">

    <a href="#page1" class="link">page 1</a>
    <a href="#page2" class="link">page 2</a>
    <a href="#page3" class="link">page 3</a>

    <div id="page1">TONS OF TEXT HERE</div>

    <div id="page2">A BIT OF TEXT HERE</div>

    <div id="page3">BUNCH OF IMAGES</div>

</div>

There are different divs fading in/out, each needing a different height. The width of the pages is also dynamic but doesn't need animation, just stretches/shrinks with viewport.

Thanks.

like image 494
Windbrand Avatar asked Jan 13 '23 23:01

Windbrand


1 Answers

DEMO http://jsfiddle.net/zbB3Q/

Animate doesn't know the end height. You'll need to get it then animate, but to do that you have to quickly set the height and return to what it was before animating.

function setContainerHeight() {
    var heightnow=$(".pagecontainer").height();
    var heightfull=$(".pagecontainer").css({height:'auto'}).height();

    $(".pagecontainer").css({height:heightnow}).animate({
        height: heightfull
    }, 500);
}
like image 199
Popnoodles Avatar answered Jan 19 '23 10:01

Popnoodles