binoculars
binoculars

Reputation: 2274

Simple loop for images

I'm trying to build a simple image slider (but using a fade effect). Every two seconds, the image should change to another image. At the end, it should call repeat_sponsor() again, to start over, so it becomes a loop.

I've written this (highly ineffective) code for 5 images. Turns out I'm going to need it for around 50 images. My editor just freezes when I add too much code.

I've tried using while-loops, but I just can't figure it out how to do this the right way. Anyone who can help me with this?

  function repeat_sponsor()
  {
      $("#sponsor2").hide();
      $("#sponsor3").hide();
      $("#sponsor4").hide();
      $("#sponsor5").fadeOut("slow");
      $("#sponsor1").fadeIn("slow", function() {
          setTimeout(function(){$("#sponsor2").fadeIn("slow", function() {
                    setTimeout(function(){$("#sponsor3").fadeIn("slow", function() {
                              setTimeout(function(){$("#sponsor4").fadeIn("slow", function() {
                                        setTimeout(function(){$("#sponsor5").fadeIn("slow", ...

Upvotes: 0

Views: 109

Answers (3)

epascarello
epascarello

Reputation: 207501

(function (){

    var cnt = 50;  //set to the last one... 
    var max=50;
    function show() { 
        $("#sponsor" + cnt).fadeOut("slow"); //if you want the fadeout to be done before showing next, put the following code in the complete callback
        cnt++; 
        if(cnt>max) {
            cnt=1; 
        }
        $("#sponsor" + cnt).fadeIn("slow"); 
        window.setTimeout(show, 2000);
    }
    show();
})();

But the real issue is the fact you are loading tons of images from the start. You will be better off changing it so you only have a small subset of images and change the source.

Upvotes: 1

jterry
jterry

Reputation: 6269

Just run a function every two seconds with setInterval and appropriately target your different sponsor divs:

var i = 1;
var max = 50;

setInterval(function() {
    // Could target all other sponsor images with a class "sponsor"
    $('.sponsor').fadeOut();

    // Execute code on the target
    $("#sponsor" + i).fadeIn();

    if (i === max) {
        i = 0;
    }

    i++;

}, 2000);

Upvotes: 0

Sjoerd de Wit
Sjoerd de Wit

Reputation: 2413

You should use some sort of for loop and a class for hiding the images. and add a max value that if checks out resets c & i

 var i=0;
 var c=1;     
 function repeat_sponsor()
 { 
   $("#sponsor"+i).fadeOut("slow");
   $(".sponsers").hide()
   $("#sponsor"+c).fadeIn("slow", function() {
      window.setTimeout(repeat_sponsor(), 3000);
    }
   i++;
   c++;
 }

Upvotes: 0

Related Questions