Reputation: 3
I have a simple image slider that I got off of the internet. I don't know much JQuery at all, just what I understand from reading the code I have. The code has an image slider that advances every 8 seconds, and has two buttons that will advance the images on click, either forwards or backwards. My problem is that when I click on the button to advance, the 8 second timer does not reset such that if I click 6 seconds into the interval, the image goes to the third image 2 seconds later. Attached is my JQuery
code. I tried adding setInterval
to the moveLeft()
and moveRight()
functions but it did not work correctly. I'm sorry for my lack of JQuery
knowledge, I learned basic JavaScript
in school and haven't used it much if at all since. Attached is the code I currently have.
jQuery(document).ready(function ($) {
setInterval(function () {
moveRight();
}, 8000);
var slideCount = $('#slider ul li').length;
var slideWidth = $('#slider ul li').width();
var slideHeight = $('#slider ul li').height();
var sliderUlWidth = slideCount * slideWidth;
$('#slider').css({ width: slideWidth, height: slideHeight });
$('#slider ul').css({ width: sliderUlWidth, marginLeft: - slideWidth });
$('#slider ul li:last-child').prependTo('#slider ul');
function moveLeft() {
$('#slider ul').animate({
left: + slideWidth
}, 1000, function () {
$('#slider ul li:last-child').prependTo('#slider ul');
$('#slider ul').css('left', '');
});
};
function moveRight() {
$('#slider ul').animate({
left: - slideWidth
}, 1000, function () {
$('#slider ul li:first-child').appendTo('#slider ul');
$('#slider ul').css('left', '');
});
};
$('a.control_prev').click(function () {
moveLeft();
setInterval(function () {
moveRight();
}, 8000);
});
$('a.control_next').click(function () {
moveRight();
setInterval(function () {
moveRight();
}, 8000);
});
});
Upvotes: 0
Views: 32
Reputation: 5107
You're having this problem because whenever you create a new Interval for moving right, your previous intervals still exist. I recommend you ensure that you have only one Interval by having a dedicated function to cancel and reinitialize:
var slideInterval = setInterval(function() {
moveRight();
}, 8000);
function resetInterval() {
clearInterval(slideInterval);
slideInterval = setInterval(function() {
moveRight();
}, 8000);
}
Then, simply call this function on click:
$('a.control_prev').click(function() {
moveLeft();
resetInterval();
});
$('a.control_next').click(function() {
moveRight();
resetInterval();
});
Upvotes: 1