Christos K
Christos K

Reputation: 3

jquery for loop showing hiding elements

I have a problem with a for loop in jQuery. I'm trying to build an ads section which will rotate dynamically to the last ad.

Unfortunately, jQuery gives me a static value for my incrementor.

Here is my code

function ads(){

   var i = 0;

   for(i=0; i<=3; i++){    
      $("#adBox").delay(5000).hide("slide", { direction: "up" }, 1000);    
      $("#adBox").delay(1000).show("slide", { direction: "right" }, 1000);    
      $("#adContent").load("adPage" +i+".php");
   }
}    
ads();

Upvotes: 0

Views: 156

Answers (1)

dgvid
dgvid

Reputation: 26633

There are a couple of things going on here that might be relevant:

  • There's nothing obviously wrong with the for loop syntax. If you add console.log("i: " + i); inside the loop, you should see four lines written to the browser's JavaScript console when this code executes, e.g.:
i: 0
i: 1
i: 2
i: 3
  • Each time the loop executes, the following things will happen, in this order:

    1. A delay of 5 seconds is added to the animation queue for element #adBox, then a slide up animation is added to the queue.
    2. Immediately after those items are added to the queue, without waiting for the delay or animation to begin, another delay and a slide right animation are added to the same element's queue.
    3. Without waiting for either of the delays or animations to execute, a call is made to get "adPage" + i + ".php". Once the page is returned, it will be loaded into element #adContent. However, the .load() method returns immediately, without waiting for the page to be retrieved or loaded.
  • The for loop probably completes all four iterations before the first call to .load() has even completed.

  • Finally, just a note about terminology: The for loop is built-in to JavaScript. It has nothing to do with jQuery, which is a JavaScript library.

I suspect that what you really want to happen is something like this:

function ads(i) {
    if (i <= 3) {
        $("#adBox").delay(5000).hide("slide", { direction: "up" }, 1000, function() {
            $("#adBox").delay(1000).show("slide", { direction: "right" }, 1000, function() {
                $("#adContent").load("adPage" + i +".php", function() {
                    ads(i + 1);
                });
            });
        });
    }
}

Those anonymous function arguments I'm passing to hide, show, and load are callback functions. They will be executed only after each function completes.

Upvotes: 1

Related Questions