Andy
Andy

Reputation: 1432

JQuery animation, not working as intended

Here are two examples that I have tried, neither of which work as intended.

http://jsfiddle.net/AndyMP/atyWW/1/ and http://jsfiddle.net/AndyMP/atyWW/4/

What I want to do is fade the top block out and animate/slide the lower block up. In the first example it jumps into place after the top block is hidden and in the second, it leaves a space at the bottom of the container DIV (presumably because I haven't hidden the top DIV).

Any help would be very appreciated.

Upvotes: 1

Views: 192

Answers (3)

Praveen Lobo
Praveen Lobo

Reputation: 7187

Add this code to adjust the height of the container - $(".container").animate({height:$(".middle").height()},600);

http://jsfiddle.net/atyWW/26/

EDIT: Some explanation - @Jon Taylor's answer explains what happens exactly. The code I provided, sets the height of the container, however, the top DIV is still behind middle div. Note that if you have overflow property set to auto instead of hidden and if the top is taller than middle, scroll bars will appear(which can be removed with jQuery anyway). Check this example.

Note the code in the last example - it uses $top.height() to pick up the value instead of hard coding it to 40px. You don't have to keep updating it for any change in CSS.

Upvotes: 1

Try that :

$(function(){ 
    $(".disappear").click(function(){
        $(".top").fadeOut(250,function(){
            $(".middle").animate({top:0}, 600);
        });

    });
});

with that css :

.top {
    position: absolute;
    top: 0;
    left: 0;
    height: 40px;
    width: 400px;
    background: green;
}
.middle {
    position: absolute;
    left: 0;
    top: 40px;
    height: 200px;
    width: 400px;
    background: red;
}

Live demo : http://jsfiddle.net/atyWW/19/

Upvotes: 1

Jon Taylor
Jon Taylor

Reputation: 7905

The problem is that your top is already 0 and so animating this is not doing anything, the reason its skipping up is because you are calling hide.

You could once the opacity of the top element has changed to 0 then modify the height of the top element as follows. I would also recommend using callbacks rather than delays, unless of course you need the second animation to start before the first has ended in which case stick with delays but the following code should give you an example of where you should go from here.

$(".disappear").click(function(){
    $(".top").fadeTo(250,0, function() {
        $(".top").animate({height:0},600);
    });
});

jsFiddle attached

Alternatively instead of hiding the top element and animating the height of the top element you could animate the margin-top of the bottom element.

Upvotes: 3

Related Questions