Reputation: 141
I have an image slider that changes images every 5 seconds, but I want the slider to pause when I hover over the div img. Is there a way to pause the 'theRotator' function on hover and then restart it after the mouse moves out of the div? Thanks all!
function theRotator() {
//Set the opacity of all images to 0
$('div.rotator ul li').css({opacity: 0.0});
//Get the first image and display it (gets set to full opacity)
$('div.rotator ul li:first').css({opacity: 1.0});
//Call the rotator function to run the slideshow,
setInterval('rotate()',5000);
}
$(document).ready(function() {
//Load the slideshow
theRotator();
$('div.rotator').fadeIn(1000);
$('div.rotator ul li').fadeIn(1000); // tweek for IE
});
Upvotes: 2
Views: 5093
Reputation: 35399
You'll want to retrieve the interval handle that is returned by the setInterval
function. Also, I used mouseenter
and mouseleave
as they are better suited for the functionality you want.
function theRotator() {
//Set the opacity of all images to 0
$('div.rotator ul li').css({opacity: 0.0});
//Get the first image and display it (gets set to full opacity)
$('div.rotator ul li:first').css({opacity: 1.0});
//Call the rotator function to run the slideshow,
window.rotatorInterval = setInterval(rotate,5000);
}
$(document).ready(function() {
//Load the slideshow
theRotator();
$('div img').mouseenter(function(){
clearInterval(window.rotatorInterval);
}).mouseleave(function() {
window.rotatorInterval = setInterval(rotate, 5000);
});
$('div.rotator').fadeIn(1000);
$('div.rotator ul li').fadeIn(1000); // tweek for IE
});
Upvotes: 1
Reputation: 337560
You simply need to clear the timeout on mouseover, and then recreate it on mouseout, like this:
var interval;
function theRotator() {
$('div.rotator ul li').css({opacity: 0.0});
$('div.rotator ul li:first').css({opacity: 1.0});
interval = setInterval(rotate, 5000);
}
$(document).ready(function() {
theRotator();
$('div.rotator').fadeIn(1000);
$('div.rotator ul li').fadeIn(1000); // tweek for IE
$('div.rotator ul li').hover(function() {
clearInterval(interval);
},
function() {
interval = setInterval(rotate, 5000);
});
});
Upvotes: 0
Reputation: 716
You could do something like
var rotate = true;
$('img').on({
mouseenter: function() {
rotate = false;
},
mouseleave: function() {
rotate = true;
}
});
and check that flag in your rotate()
function
Upvotes: 0