Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery animate from CSS "top" to "bottom"

I'm looking to animate a div element from an absolute top position to an absolute bottom position on the page load.

The combination of CSS and jQuery code below fails to move anything:

CSS

#line-three {
    position:absolute;
    width:100%;
    left:0px;
    top:113px;
}

jQuery

 $("#line-three").animate({
    bottom: "100px",
    }, 1200);

Thank you for your help!

EDIT:

I've tried changing it to this (as per graphicdevine's suggestions) but still no cigar:

var footerOffsetTop = $('#line-three').offset().bottom;
  $('#line-three').css({position:'absolute',top:'',bottom:footerOffsetTop})
  $("#line-three").delay(100).animate({
    bottom: '100px',
    }, 1200);
like image 830
bravokiloecho Avatar asked Dec 15 '11 10:12

bravokiloecho


2 Answers

I eventually came up with a solution...

Basically you animate from the old top position to another position also relative to to the top which you calculate by taking the window height and subtracting (1) the desired position from the bottom, and (2) the height of the element you want to animate. Then, at the end of the animation add a callback to change the css so as the element is then position with a bottom value and a top auto value

Here's the jQuery script:

$('#click').click(function () {

    var windowHeight = $(window).height();
    var lineHeight = $('#line').height();
    var desiredBottom = 100;

    var newPosition = windowHeight - (lineHeight + desiredBottom);

    $('#line').animate({top:newPosition},1000,function () {
        $('#line').css({
            bottom: desiredBottom,
            top: 'auto'
        });
    });

});

You can see it working in this jsFiddle

like image 141
bravokiloecho Avatar answered Oct 09 '22 03:10

bravokiloecho


You can set top:auto with .css method and then animate:

$(document).ready(function(){
   $("#line-three").css({top:'auto'});   
   $("#line-three").animate({bottom:'100px'}, 200)   
})

EDIT:

You can play with size of body/screen and convert top position to bottom position and then animate to the desired bottom position:

$(document).ready(function(){
  var bodyHeight = $('body').height();
  var footerOffsetTop = $('#line-three').offset().top;
  var topToBottom = bodyHeight -footerOffsetTop;

  $('#line-three').css({top:'auto',bottom:topToBottom});
  $("#line-three").delay(100).animate({
    bottom: '100px',
  }, 1200); 

})

Example: http://jsfiddle.net/reWwx/4/

like image 42
davidmatas Avatar answered Oct 09 '22 03:10

davidmatas