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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With