Matt Fritze
Matt Fritze

Reputation: 325

javascript - Delete and shift elements after animation

I have a list of panels with IDs in the form npc_parent_i (where i is its index), all of which have a class npc-container. They form a vertical line with npc_parent_1 at the top. I would like to accomplish this animation:

While npc_parent_1 fades out, all of the npc_parent_i beneath the first move towards the top of the page, eventually completely overlapping npc_parent_1. Once the animation is finished, I want to remove the element npc_parent_1.

Here is my current code:

var panelHeight = $('#npc_parent_1').outerHeight();
$.when(
    $('#npc_parent_1').fadeOut(750),
    $('.npc-container').animate({top:-panelHeight}, 750)
).then(
    function(){
        var npcPanel = document.getElementById('npc_parent_1');
        npcPanel.parentNode.removeChild(npcPanel);
        $('.npc-container').css('top', '0px');
    }
);

The animation runs correctly, but when the element gets deleted, the rest of the panels shift up, then back down as their top values are set back to 0. I think the issue may be that npc_panel_1 also has the class npc-container, but it doesn't move during the animation.

How can I keep the panels in place while deleting the element above them?

Upvotes: 0

Views: 1044

Answers (2)

alettieri
alettieri

Reputation: 396

fadeOut will set the opacity then sets the element to display: none. Which removes it from the layout flow. Animating the opacity property is a better bet.

Upvotes: 0

Rob Schmuecker
Rob Schmuecker

Reputation: 8954

I think fadeOut was causing you troubles. Have a look at this code,

$(document).ready(function () {
    $.when(
    $('#test1').animate({
        opacity: 0
    }, 750),
    $('.npc-container').not('#test1').animate({
        top: '-200px'
    }, 750)).then(

    function () {
        var npcPanel = document.getElementById('test1');
        npcPanel.parentNode.removeChild(npcPanel);
        $('.npc-container').css('top', '0px');
    });
});

I have also set the position of .npc-container to relative

Demo: http://jsfiddle.net/robschmuecker/958e6/ notice also that jQuery UI is needed for animate to work properly.

Upvotes: 2

Related Questions