I have a given list of images, presented as thumbnails:
<ul id="thumbs">
<li class="small-img"><img src="images/feature1.png" /></li>
<li class="small-img"><img src="images/feature2.png" /></li>
<li class="small-img"><img src="images/feature3.png" /></li>
</ul>
I use jQuery so that, when the user clicks on an image, it replaces the featured image in a div (which I got from another StackOverflow Ask):
$('#thumbs img').click(function(){
$('div.feature-photo img').hide().attr('src',$(this).attr('src')).fadeIn();
});
My question is: Is there a way to make it into a slideshow? Maybe automatically "click" on the next picture every 5 seconds? Does setInterval
play a part in this? I'm trying to be really basic about it, and avoid using more plugins than I have to. (But if there is no other way, I will consider it..)
Would appreciate any kind of help.
You need to think in terms of what your code should do, not what the user does that triggers your code. So rather than "automatically 'click'", you just want your code to automatically show the next image.
So the first step is to move your code out of the
click
handler:And then the question becomes: How do I call
showImage
every five seconds with the "next" image. Well, first we'll want to remember what the "current" image is. Easy enough to modify ourshowImage
to do that:So then we just need a trigger to occur in five seconds. You can use
setInterval
, but I find it's really easy to have it get out of control, so I use a chained series ofsetTimeout
instead, where each one sets up the next. And what would be a good trigger for that? Well, five seconds after the user clicks an image, so probably right there inshowImage
:Okay, so what should
nextImage
look like? I'd say we probably want to usecurrent
, perhaps:You might kick things off at the beginning by showing the first image:
So bringing that all together, and making sure we wrap it in a scoping function so we don't create global symbols:
(Or instead of a vanilla scoping function, you might use jQuery
ready
.)The above is fairly rough, and completely untested, but you get the idea.
setInterval might be the answer to your question
You can go with the plain JQuery way, if you like. Here's my try
And you can find it in action here
You could use
But you have to keeep in mind that if the user reloads the page, the Timeout starts from zero !
You may easily calculate the next image within the switch function. This way you won't mess up your var space ;)