0


I wrote this code: 3 clouds flying over my website.
Question is: how I can make this shorter? (ex: in one function or something like that)

var x1 = 1500-Math.random()*2000;
function animateDivers1() {
    var y1 = 500-Math.random()*600;
    $('.section1 .cloud1').css('left', x1);
    $('.section1 .cloud1').css('top', y1);
    x1 = -400;  
    var time = 15000+Math.random()*10000;
    $('.section1 .cloud1').animate({
        left: x1+2000
    }, time, "linear", animateDivers1
)}
animateDivers1();


var x2 = 1500-Math.random()*2000;
function animateDivers2() {
    var y2 = 500-Math.random()*600; 
    $('.section1 .cloud2').css('left', x2);
    $('.section1 .cloud2').css('top', y2);
    x2 = -400;  
    var time = 15000+Math.random()*10000;
    $('.section1 .cloud2').animate({
        left: x2+2000
    }, time, "linear", animateDivers2
)}
animateDivers2();


var x3 = 1500-Math.random()*2000;
function animateDivers3() {
    var y3 = 500-Math.random()*600; 
    $('.section1 .cloud3').css('left', x3);
    $('.section1 .cloud3').css('top', y3);
    x3 = -400;  
    var time = 15000+Math.random()*10000;
    $('.section1 .cloud3').animate({
        left: x3+2000
    }, time, "linear", animateDivers3
)}
animateDivers3();

and of course I want add more - but duplicate this code seems silly

1
  • 1
    Why don't you just iterate through the clouds in .section1? Commented Nov 23, 2016 at 23:56

1 Answer 1

1
function animateDivers(cloud, iter=0) {
    var x = (iter == 0) ? 1500-Math.random()*2000 : -400
    var y = 500-Math.random()*600; 
    $('.section1 '+cloud).css('left', x);
    $('.section1 '+cloud).css('top', y);
    x = -400;  
    var time = 15000+Math.random()*10000;
    $('.section1 '+cloud).animate({
        left: x+2000
    }, time, "linear", function() { animateDivers(cloud, iter+1) }
)}

for (i=1;i<=3;i++) { 
    animateDivers(".cloud" + i); 
}
Sign up to request clarification or add additional context in comments.

1 Comment

this should do the trick, after the first iteration, the x value is always -400.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.