Get image slider for auto play

I am trying to get my own image slider for automatic playback at intervals of 4000 milliseconds. I tried using setTimeout , but I can't get it to work. I would be grateful if someone could help me. Here is an example slider:

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

Any ideas how I can get it to play automatically?

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

+7
jquery image timeout
source share
1 answer

I managed to set up auto play, which works fine using a combination of setTimeout and recursion.

I gave the nextimage() function the autoplay parameter, 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 an autostart loop:

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

Check out the demo here, built mostly from what you provided, with a few changes for auto play: http://jsfiddle.net/bVjkP/

In short, you pass a boolean value to the nextimage () function to tell you whether to start auto play. Then you just call the initial setTimeout to get the ball. The trick with this method is that you have to call an anonymous function via setTimeout, which calls the nextimage function with the autoplay parameter set to true, because you cannot pass parameters when calling the function using setTimeout. This is similar to a method of binding functions to events, such as clicking or freezing using jQuery.

+2
source share

All Articles