user269890
user269890

Reputation:

I'm trying to make a loop with jQuery

All I need it to do is run the function animateAds over and over. Can anyone help? This is my code:

function animateAds(n) {
    $('#ad_1').fadeIn('slow', function (){
        $('#ad_1').delay(100).fadeOut('fast', function (){
            $('#ad_2').fadeIn('slow');
        });
    });
};

$(document).ready(function() {
    for (n = 0; n < 10; n++) {
    animateAds(n);
    }
});     

Upvotes: 1

Views: 302

Answers (4)

user113716
user113716

Reputation: 322452

Your code shows a limit of 10, but your question sort of sounds like you want it to be perpetual.

Here's an example of how it would run perpetually. If you want the limit, then it would be a simple reworking of the if() statement in the callback.

$('document').ready(function() {    
    var elements = ['#ad_1','#ad_2'];
    var i = 0;
    var limit = elements.length;
    function rotateAds() {
        $(elements[i]).fadeIn(400);
        $(elements[i]).delay(1000).fadeOut(200,function(){
                                                    i++;
                                                    if(i == limit) i = 0;
                                                    rotateAds();
                                                })
    }
    rotateAds();
});

Does this seem close to what you were looking for?

You can add as many elements to the array as you wish, since it simply counts the length of the array.

Upvotes: 1

JAL
JAL

Reputation: 21563

<!doctype html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>
var i=0;
function animateAds() {
    if(i==9){return;}
    $('#ad_2').fadeOut('fast',function(){
      $('#ad_1').fadeIn('slow', function (){
        $('#ad_1').delay(100).fadeOut('fast', function (){
          $('#ad_2').fadeIn('slow', function(){i++;animateAds();});
        });
      });
    });
};
$(document).ready(function() {
    animateAds();
    });
</script>
</head>
<body>


<img id='ad_1' style='display:none' src='http://sstatic.net/so/img/logo.png'>
<br>

<img id='ad_2' src='http://sstatic.net/so/img/logo.png'>

I'm not sure if this ideal, but it works as a self contained page. Is this what you're trying to do?

Upvotes: 2

George Godik
George Godik

Reputation: 1716

maybe you need to add a 'var' to the for loop, unless n is declared elsewhere

for( var n = 0 ; .... 

Upvotes: 0

aefxx
aefxx

Reputation: 25249

setInterval(function(){animateAds()}, 100);

This would call your function 10 times a second (100 ms each). I stripped the n parameter as it's not used in your code.

Regards.

Upvotes: 1

Related Questions