Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - repeat animation for X times

How can I write this more efficiently?

HTML

<div class="navigation-left">left</div>
<div class="navigation-right">right</div>

Js

$(document).ready(function(){
    var offs = 0,
        speed = 700;

    $('.navigation-left').animate({
        left: offs,
        opacity: 0
    }, speed)
    .animate({
        left: 70 + offs,
        opacity: 100
    }, speed)
    .animate({
        left: offs,
        opacity: 0
    }, speed)
    .animate({
        left: 70 + offs,
        opacity: 100
    }, speed)
    .animate({
        left: offs,
        opacity: 0
    }, speed)
    .animate({
        left: 70 + offs,
        opacity: 100
    }, speed)
    .animate({
        left: offs,
        opacity: 100
    }, speed);

    $('.navigation-right').animate({
        right: offs,
        opacity: 0
    }, speed)
    .animate({
        right: 70 + offs,
        opacity: 100
    }, speed)
    .animate({
        right: offs,
        opacity: 0
    }, speed)
    .animate({
        right: 70 + offs,
        opacity: 100
    }, speed)
    .animate({
        right: offs,
        opacity: 0
    }, speed)
    .animate({
        right: 70 + offs,
        opacity: 100
    }, speed)
    .animate({
        right: offs,
        opacity: 100
    }, speed);
});

​ See the jsfiddle here: http://jsfiddle.net/klawisz/nESMD/

like image 633
klawisz Avatar asked Mar 27 '12 13:03

klawisz


2 Answers

Using jQuery and a setTimeout()

(function anim (times){
    $('.left').animate({left:70,   opacity:0},700).animate({left:0,  opacity:1},700);
    $('.right').animate({right:70, opacity:0},700).animate({right:0, opacity:1},700);
    if(--times) return setTimeout(anim.bind(this, times), 1400);
}( 5 )); // <--- pass initial N of times
.left, .right {position:absolute; width:50px; height:50px; background:red;}
.left {left:0;}
.right {right:0;}
<div class="left"></div>
<div class="right"></div>
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
like image 61
Roko C. Buljan Avatar answered Sep 29 '22 14:09

Roko C. Buljan


Something like this?

$(document).ready(function(){
    var offs = 0,
        speed = 700,
        times = 10;

    var counter = 0;
    var step = function(){
        if(counter < times) {
            counter++;
            $('.navigation-left').animate({
                left: offs,
                opacity: 0
            }, speed)
            .animate({
                left: 70 + offs,
                opacity: 100
            }, speed);

            $('.navigation-right').animate({
                right: offs,
                opacity: 0
            }, speed)
            .animate({
                right: 70 + offs,
                opacity: 100
            }, speed, null, step);
        }
    };

    step();
});
like image 29
Aleksandar Vucetic Avatar answered Sep 29 '22 14:09

Aleksandar Vucetic