Greg
Greg

Reputation: 3063

Keep playing animation in javascript

I'd like to achieve something like this (fading animated arrow at the bottom of the header picture indicating that the user needs to scroll down). In order to to this I'm planning to use the code below. The issue is that the animation only plays 1x whereas I would like it to play continuously (in a way that wouldn't take too much resource). See http://jsfiddle.net/ZN3aD/

$('.icon').css('display', 'block');
$('.icon').animate({ opacity: 1 }, 0);
$('.icon').animate({ opacity: 0, top: "100px" }, 'slow');

Upvotes: 2

Views: 190

Answers (4)

webkit
webkit

Reputation: 3369

Here's a solution:

var arwtimer = 0;

$('.icon').css('display', 'block');
$('.icon').animate({ opacity: 1 }, 0);


function pleaseScroll() {
    $('.icon').css({ top: 80 }, 0).animate({ opacity: 1 }, 222);;

    $('.icon').delay(999).animate({ opacity: 0, top: "100px" }, 999);
}

arwtimer = setInterval(pleaseScroll, 4000);

http://jsfiddle.net/rvvb2/

Upvotes: 0

dfsq
dfsq

Reputation: 193261

I would recommend you to use CSS animation:

.icon {
    ...
    -webkit-animation: icon 1.2s infinite;
    animation: icon 1.2s infinite;
}

@-webkit-keyframes icon {
    from {
        opacity: 1;
        top: 80px;
    }
    to {
        opacity: 0;
        top: 100px;
    }
}
@keyframes icon {
    from {
        opacity: 1;
        top: 80px;
    }
    to {
        opacity: 0;
        top: 100px;
    }
}

It will work in IE10+.

Demo: http://jsfiddle.net/ZN3aD/6/

If you anyway want old browsers support then take a look at James Donnelly answer. Or you can use this code snippet:

(function animate() {
    $('.icon').animate({ opacity: 1, top: 80 }, 0)
    .animate({ opacity: 0, top: 100 }, 'slow', animate);
})();

Demo: http://jsfiddle.net/ZN3aD/8/

Upvotes: 5

jacek_podwysocki
jacek_podwysocki

Reputation: 807

This should do the trick. Adding setInterval will repeat the animation placed inside function:

     function runAnimation(){

     $('.icon').css('display', 'block');
     $('.icon').animate({ opacity: 1 }, 0);
     $('.icon').animate({ opacity: 0, top: "100px" }, 'slow');

                }

var interval = setInterval(runAnimation,1000);

Upvotes: -1

James Donnelly
James Donnelly

Reputation: 128791

Set it up as a recursive function which calls itself when the animation completes. (JSFiddle demo).

$('.icon').css('display', 'block');

function animate() {
    // jQuery's CSS method should be used instead of an instant animation
    $('.icon').css({ opacity: 1 });

    $('.icon').animate({
        opacity: 0,
        // jQuery handles the units for you, so you can just use a number here
        top: 100
    },'slow', function() {
        // I assume you want the top value to be reset here
        $(this).css({ top: 80 });

        // Call the animate() function again when the animation has completed
        animate();
    });
}

// Trigger the animation initially
animate();

Upvotes: 4

Related Questions