Question

I'm writing a slider in jQuery. I'd like it to have an unknown number of boxes that slide upwards until the last one is reached, then it slides down to the first box and loops. I want to write it myself and be light on the jQuery. I've reached a snag in my creation!

Here's the jQuery:

function catslide() {
    var speed = 500;
    var delay = 1000;
    var move  = $j( "#Fader" ).height();
    for ( var i = 0; i < $j("div.slide").length; i++ )
    {
        $j( "#Fader .slide" ).first().delay(delay).animate({ 'margin-top':(move*i)*-1 }, speed);
    }
    catslide();
};
catslide();

in JSFiddle: http://jsfiddle.net/3nY4M/1/

It works, but check out the page load delay! If you push "run" in the JSFiddle and watch the page load in your Firefox tab you'll see the page stop loading for a couple of seconds. In Chrome you just see extra load time. Removing the top catslide(); fixes the issue, but of course the slider does not loop.

I've tried various methods including checking to see if the slide is the last one in the for loop and adding a callback, each with the same result. Any ideas?

Was it helpful?

Solution

I've found the answer, and updated my JSFiddle: http://jsfiddle.net/3nY4M/2/

The line that has the callback:

$j( "#Fader .slide" ).first().delay(delay).animate({ 'margin-top':(move*i)*-1 }, speed, catslide);

runs the code without load time delay. I had been previously (and incorrectly) been using this line:

$j( "#Fader .slide" ).first().delay(delay).animate({ 'margin-top':(move*i)*-1 }, speed, catslide());

(Note the brackets in the callback.) Removing the brackets improves pages load no end.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top