Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get image slider to auto play

I am trying to get my own image slider to auto play with an interval of 4000 milliseconds. I've tried using setTimeout but I cannot seem to get it to work. I would appreciate it if someone could help me out. Here is example of the slider:

http://www.matthewruddy.com/slider-intervalissue/

Any ideas how I can get it to auto play?

Here is the jQuery code:

$(document).ready(function(){
    var images = $('.slider li');
    var slides = images.length;
    var sliderwidth = 500;
    var currentimage = 0;
    var containerwidth =  sliderwidth*slides;
    var autoplay = 4000;

    $('.slider').css('width', containerwidth);

    $('#next').bind('click',nextimage);

    function nextimage(){
        if(currentimage<slides-1){
            currentimage++;
            $('.slider').animate({left:-sliderwidth*(currentimage)},{duration:800,easing:'easeInOutCubic'});
        }
        else{
            currentimage = 0;
            $('.slider').animate({left:0},{duration:800,easing:'easeInOutCubic'})
        }
    };

});

Thanks, Matthew

like image 634
Matthew Ruddy Avatar asked Aug 16 '10 22:08

Matthew Ruddy


1 Answers

I was able to set up an autoplay that runs quite nicely, using a combination of setTimeout and recursion.

I gave the nextimage() function a parameter autoplay, which is a boolean. Then I added the following line at the end of the function:

if (autoplay) { setTimeout(function() { nextimage(true); }, 4000); }

Finally I added this line at the end of the script, to get the autoplay loop going:

setTimeout(function() { nextimage(true); }, 4000);

Check out the demo here, constructed mostly from what you provided, with a few modifications to do the autoplaying: http://jsfiddle.net/bVjkP/

In short, you pass a boolean into the nextimage() function, to tell it whether or not to begin an autoplay. Then you simply call an initial setTimeout to get the ball rolling. The trick with this method is that you have to call an anonymous function through the setTimeout, which calls the nextimage function with autoplay set to true, because you can't pass parameters when calling a function with setTimeout. This is similar to the method for binding functions to events such as click or hover using jQuery.

like image 67
Ender Avatar answered Oct 20 '22 20:10

Ender