Slevin
Slevin

Reputation: 4222

Animate css attributes: from "top" to "bottom"

Update 2

I figured it out. If anyone have similar problems, see my answer.

Update

jsFiddle: http://jsfiddle.net/HBUAx/

Post

I'm working on a few animations with jQuery. I have 3-4 elements which should slide in from the top. I defined their positions with css:

#element-1 {
    top:124px;
    left:0px;
    right:auto;
    bottom:auto;
}

#element-2 {
    top:230px;
    left:670px;
    right:auto;
    bottom:auto;        
}

#element-3 {
    top:auto;
    left:0px;
    right:auto;     
    bottom:100px;
}

Then I save their positions initial on pageload, cause i have to manipulate the css value to

top: -1000px

to hide them and make the "slide in from top" animation possible.

var image_margins = [];
$('img').each(function() {
    var obj = $(this),
        id = obj.attr('id'),
        mtop = obj.css('top'),
        mleft = obj.css('left'),
        mright = obj.css('right'),
        mbottom = obj.css('bottom');

    // save alle margins in array
    image_margins[id] = {mtop:mtop,mleft:mleft,mright:mright,mbottom:mbottom};

    // hide all content elements 
    obj.css({'top':'-1000px'});

}); 

When the user clicks the animate button, the elements should slide to their saved positions. The problem: i can't remove the top attribute. Some elements only have bottom margins. I tried to set top to auto or '', but it's always 0px in DOM inspector. And bottom don't work if top is set. How can i get rid of the top attribute?

$('.button').click(function(){
    $('img').each(function() {
        var image = $(this),
            id = image.attr('id'),
            timeout = 0;

        setTimeout(function() {
            var mtop, mleft, mright, mbottom;
            if (image_margins[id].mtop != 'auto') { mtop = image_margins[id].mtop; } else { mtop = ''; }
            if (image_margins[id].mleft != 'auto') { mleft = image_margins[id].mleft; } else { mleft = ''; }
            if (image_margins[id].mright != 'auto') { mright = image_margins[id].mright; } else { mright = ''; }
            if (image_margins[id].mbottom != 'auto') { mbottom = image_margins[id].mbottom; } else { mbottom = ''; }
            image.animate({'top':mtop,'left':mleft,'right':mright,'bottom':mbottom},500);

        },timeout);
        timeout = timeout + 200;
    }); 
});

Upvotes: 1

Views: 769

Answers (2)

Slevin
Slevin

Reputation: 4222

OK, i figured it out. I have to check if the element have a defined top position. If not, i have to hide it with a large bottom value.

See: http://jsfiddle.net/gg33z/1/

Upvotes: 1

Kristoffer K
Kristoffer K

Reputation: 2053

Try this:

$(element).css('top', '');

This should unset the "top" value.

Upvotes: 0

Related Questions