Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop .animate JQuery

I am working with a single div with an image inside. I need the animation to scroll from right-left of the page and then comeback to the right and continue in a loop. I have looked over many posts on here but am not able to get the script working properly.

'$(document).ready(function(){
    function loop() {

       $('#clouds').animate({left: '+=1400',},50000, 'linear', function(){
           loop();
       });

HTML

< div id="clouds">< img border="0" alt="animated clouds" src="/images/clouds.png" />< /div>

CSS

#clouds {
    position:absolute;
    z-index:500;
    right:0px;
    top:10px;
}
like image 512
ac12 Avatar asked Jul 09 '12 19:07

ac12


People also ask

How do you animate in jQuery?

jQuery Animations - The animate() Method. The jQuery animate() method is used to create custom animations. Syntax: $(selector).animate({params},speed,callback); The required params parameter defines the CSS properties to be animated. The optional speed parameter specifies the duration of the effect.

Which method is used to create custom animations in jQuery?

jQuery Animations - The animate () Method The jQuery animate () method is used to create custom animations.

What is animate () function in CSS?

A function that is called once the animation on an element is complete. The .animate () method allows us to create animation effects on any numeric CSS property. The only required parameter is a plain object of CSS properties.

Why is my jQuery animation not running smoothly?

Note: if attempting to animate an element with a height or width of 0px, where contents of the element are visible due to overflow, jQuery may clip this overflow during animation. By fixing the dimensions of the original element being hidden however, it is possible to ensure that the animation runs smoothly.


1 Answers

All the above answers are somewhat 'hack' solutions.

According to the jQuery documentation for animate(), the second paramter is an options object which has a parameter complete; a function that is called when the animation completes.

In OP's case, this option object would be configured as follows:

function loop() {
    $('#clouds').css({right:0});
    $('#clouds').animate({
        right: '+=1400',
    }, {
        duration: 5000, 
        easing: 'linear', 
        complete: loop
    });
}
loop();
like image 181
fullStackChris Avatar answered Oct 11 '22 21:10

fullStackChris