using jQuery .animate to animate a div from right to left?
I think the reason it doesn't work has something to do with the fact that you have the right
position set, but not the left
.
If you manually set the left
to the current position, it seems to go:
Live example: http://jsfiddle.net/XqqtN/
var left = $('#coolDiv').offset().left; // Get the calculated left position$("#coolDiv").css({left:left}) // Set the left to its calculated position .animate({"left":"0px"}, "slow");
EDIT:
Appears as though Firefox behaves as expected because its calculated left
position is available as the correct value in pixels, whereas Webkit based browsers, and apparently IE, return a value of auto
for the left position.
Because auto
is not a starting position for an animation, the animation effectively runs from 0 to 0. Not very interesting to watch. :o)
Setting the left position manually before the animate as above fixes the issue.
If you don't like cluttering the landscape with variables, here's a nice version of the same thing that obviates the need for a variable:
$("#coolDiv").css('left', function(){ return $(this).offset().left; }) .animate({"left":"0px"}, "slow");
This worked for me
$("div").css({"left":"2000px"}).animate({"left":"0px"}, "slow");
Here's a minimal answer that shows your example working:
<html><head><title>hello.world.animate()</title><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script><style type="text/css">#coolDiv { position: absolute; top: 0; right: 0; width: 200px; background-color: #ccc;}</style><script type="text/javascript">$(document).ready(function() { // this way works fine for Firefox, but // Chrome and Safari can't do it. $("#coolDiv").animate({'left':0}, "slow"); // So basically if you *start* with a right position // then stick to animating to another right position // to do that, get the window width minus the width of your div:$("#coolDiv").animate({'right':($('body').innerWidth()-$('#coolDiv').width())}, 'slow'); // sorry that's so ugly!});</script></head><body> <div style="" id="coolDiv">HELLO</div></body></html>
Original Answer:
You have:
$("#coolDiv").animate({"left":"0px", "slow");
Corrected:
$("#coolDiv").animate({"left":"0px"}, "slow");
Documentation: http://api.jquery.com/animate/