Reputation: 323
I'm working on a quick slideshow for a website. I'm still working on my Javascript/jQuery, so I could probably simplify my code in the future. Regardless, I'm using the setTimeout function to increase the currentImage variable. However, it doesn't appear to be working properly, as the images do not change as time passes. The back and next buttons still work, but it seems like it's skipping one of the images.
$(document).ready(function(){
var topofDiv = $("header").offset().top;
var height = $("header").outerHeight();
$(window).scroll(function(){
if($(window).scrollTop() > (topofDiv + height))
{
$("#nav").css("position","fixed");
}
else
{
$("#nav").css("position","static");
}
});
var currentImage = 0;
function autoPlay()
{
window.setTimeout(function(){
currentImage++;
}, 1000);
};
function slideImage()
{
if(currentImage == 0)
{
$(".img1").fadeIn(1000).show();
}
else
{
$(".img1").fadeOut(1000).hide();
}
if(currentImage == 1)
{
$(".img2").fadeIn(1000).show();
}
else
{
$(".img2").fadeOut(1000).hide();
}
if(currentImage == 2)
{
$(".img3").fadeIn(1000).show();
}
else
{
$(".img3").fadeOut(1000).hide();
}
};
slideImage();
autoPlay();
$("#next").mouseenter(function(){
$(this).css("color","black");
});
$("#next").mouseleave(function(){
$(this).css("color","white");
});
$("#back").mouseenter(function(){
$(this).css("color","black");
});
$("#back").mouseleave(function(){
$(this).css("color","white");
});
$("#next").click(function(){
clearTimeout(autoPlay);
currentImage++;
if(currentImage >= 3)
{
currentImage = 0;
}
slideImage();
});
$("#back").click(function(){
clearTimeout(autoPlay);
currentImage--;
if(currentImage < 0)
{
currentImage = 2;
}
slideImage();
});
});
Upvotes: 1
Views: 485
Reputation: 1956
Try the following code.You need to call slideimage function
inside the setInteval
and you should use setInterval
not setTimeout
.So In each 1 sec currentImage value will increase by 1 and show appropriate image.When currentImage value is greater than 3,then reset the value to zero and show the first image by calling slideimage dunction
var interval ="";
interval = window.setInterval(function(){
currentImage++;
slideImage();
if(currentImage > 3)
{
currentImage = 0;
slideImage();
}
}, 1000);
function RemoveInterval() {
clearInterval(interval );
}
Call the RemoveInterval
in the next and back button click
Upvotes: 1