I have a given list of images, presented as thumbnails:
&
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:
function showImage(img){
$('div.feature-photo img').hide().attr('src',$(img).attr('src')).fadeIn();
}
$('#thumbs img').click(function() {
showImage(this);
});
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 our showImage to do that:
var current = null;
function showImage(img){
current = img;
$('div.feature-photo img').hide().attr('src',$(img).attr('src')).fadeIn();
}
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 of setTimeout 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 in showImage:
var current = null;
var timer = 0;
function showImage(img){
current = img;
$('div.feature-photo img').hide().attr('src',$(img).attr('src')).fadeIn();
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(nextImage, 5000);
}
Okay, so what should nextImage look like? I'd say we probably want to use current, perhaps:
function nextImage() {
var $current;
if (timer) {
clearTimeout(timer);
timer = 0;
}
if (current) {
$current = $(current);
next = $current.nextAll("img")[0];
if (!next) {
$current.siblings("img")[0];
}
if (next) {
showImage(next);
}
}
}
You might kick things off at the beginning by showing the first image:
showImage($("#thumbs img")[0]);
So bringing that all together, and making sure we wrap it in a scoping function so we don't create global symbols:
(function() {
var current = null;
var timer = 0;
function showImage(img){
current = img;
$('div.feature-photo img').hide().attr('src',$(img).attr('src')).fadeIn();
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(nextImage, 5000);
}
function nextImage() {
var $current;
if (timer) {
clearTimeout(timer);
timer = 0;
}
if (current) {
$current = $(current);
next = $current.nextAll("img")[0];
if (!next) {
$current.siblings("img")[0];
}
if (next) {
showImage(next);
}
}
}
$('#thumbs img').click(function() {
showImage(this);
});
showImage($("#thumbs img")[0]);
})();
(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.