jquery: can i animate the position:absolute to position:relative?

ExodusNicholas picture ExodusNicholas · Feb 4, 2010 · Viewed 24.8k times · Source

i have a bunch of images that are positioned absolutely, i want to be able to click a button and have them all animate to where they would normally be on the page if they had the position: relative.

so is it even possible to animate from position:absolute to position:relative in jquery?

this is what i have:

$(".change_layout").click(function(){

    $(".book_img").animate({position:'relative', top:'0px', left:'0px'}, 1000)

})

Answer

Tatu Ulmanen picture Tatu Ulmanen · Feb 4, 2010

No, you cannot animate it directly but you can find out the end point and animate the position there. Something like this might work when animation to the static position:

$('img.foo').each(function() {

    var el = $(this);

    // Make it static
    el.css({
        visibility: 'hidden', // Hide it so the position change isn't visible
        position: 'static'
    });

    // Get the static position
    var end = el.position();

    // Turn it back to absolute
    el.css({
        visibility: 'visible', // Show it
        position: 'absolute'
    }).animate({ // Animate to the static position
        top: end.top,
        left: end.left
    }, function() { // Make it static
        $(this).css('position', 'static');
    });
});

It's a bit hacky, but it should work.