Animate absolute div to left:0 then to right:0 and loop

2.7k Views Asked by At

Ok, I know how to animate div's and loop the animation and stuff but this really got on my nerves, I want to animate a div to left:0; and then to right:0; and loop the animation and IT WILL NOT WORK like this...Why is that?

How do I do this?..

PS: Apparently jquery can't animate an absolute container from left:0 to right:o...but how can I get the desired animation?

Example:

Something like this will not work...:

$(document).ready(function() {   
function animateMydiv() {
$('#mydiv').animate({'left':'0px'},6000).animate({'right':'0px'},6000, animateMydiv); 
}

animateMydiv();
}); 

Here is the jsfiddle.

2

There are 2 best solutions below

3
On BEST ANSWER

As far as I understand positioning in CSS, you can't have both a right and a left value set at the same time.

So I would propose the follow. Just move it to the end of the document minus the width of the element:

$(document).ready(function() {

  var width = $(document).width() - $('#mydiv').width();

  function animateMydiv() {
    $('#mydiv').animate({'left': width + 'px'}, 6000).animate({'left': '0px'}, 6000);

  }

  animateMydiv();

}); 

Check out the fiddle: http://jsfiddle.net/bc927afp/1/

And if you want it to be endless, leave the function as you had in your example: $('#mydiv').animate({'left': width + 'px'}, 6000).animate({'left': '0px'}, 6000, animateMydiv);

0
On

As was already said in another answer: you basically can not animate from left to right. So the key to solving this, is by only using one of them.

Start position on the left:

left: 0%;
transform: translationY(0%);

End position on the right:

left: 100%;
transform: translationY(-100%);

All you have to do now is to animate the left and the transform properties. I recently wrote down a more detailed explanation and also showcased a CSS-based animation at https://medium.com/@taig/dynamically-position-and-center-an-html-element-with-css-based-on-percentage-5fea0799a589.