I have a div absolutely positioned at top: 0px
and right: 0px
, and I would like to use jquery's .animate()
to animate it from it's current position to left: 0px
. How does one do this? I can't seem to get this to work:
$("#coolDiv").animate({"left":"0px"}, "slow");
Why doesn't this work and how does one accomplish what I am looking to do?
Thanks!!
The task here is to create a slide left and right toggle effect in the JQuery, you can use the jQuery animate() method. . animate() method: It is used to change the CSS property to create the animated effect for the selected element.
The animate() method is typically used to animate numeric CSS properties, for example, width , height , margin , padding , opacity , top , left , etc. but the non-numeric properties such as color or background-color cannot be animated using the basic jQuery functionality. Note: Not all CSS properties are animatable.
jQuery Animations - The animate() Method The jQuery animate() method is used to create custom animations. Syntax: $(selector). animate({params},speed,callback);
Reverse. If you use the reverse value, the animation will play backwards. Meaning, for every animation cycle, the animation will reset to the end state. With this value, not only are the animation steps performed backwards — the timing functions are also reversed.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With