jQuery animate from “PX” to “AUTO”

April 6, 2013

so if I have the CSS property “top” equal to ‘auto and i animate it to be “30px” and I want to change it back to auto… i should be able to just do:

$('.section').animate({'top':'auto'},500);

right? WRONG! You can’t animate to auto, so how do you change it back? Sure, you can set the CSS to be that, but not useful if you want an animation with it. The solution involves some math and customization on your part, but i can go through what made it work on my end.

First you need to find out what “auto” really is. You’ll need to calculate this based on the parent elements.

var windowHeight = $('.page').height(); //height of parent div
var desiredOffset = 140; //offset from the bottom
var newPosition = windowHeight - desiredOffset+'px';

Taking this value, you can animate the CSS property of top to that value. Now if your parent is based on the window height, that top value isn’t going to work… so after your done animating it to the top for that browser height, you can then use jQuery’s CSS function to simply change back to top:auto / remove the added style you just applied. (since it should be theoretically the same location as the top CSS you just calculated to animate to. So all together it would be:

var windowHeight = $('.page').height();
var desiredOffset = 140;
var newPosition = windowHeight - desiredOffset +'px';
$('.section').animate({'top':newPosition},500);
$('.section').delay(600).stop().removeAttr('style');

Source

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive