clear interval on hover
-
14-03-2021 - |
Question
have a custom made slider which I would like to stop on hover. I've tried to clear and set the interval on hover but doesn't work properly. It stops only the first time I hover on it then if I move the mouse out and in again it doesn't stop.
here's my code:
var itvl = null;
itvl = window.setInterval(function(){scroll_()},3000);
function scroll_() {
if ($('#carousel_ul li').length > 1) {
$("#right_scroll").click();
}
}
$('#carousel_ul li').hover(function() {
window.clearInterval(itvl);
}, function() {
window.setInterval(function(){scroll_()},3000);
});
Any idea what am I doing wrong?
Thanks in advance
Mauro
Solution
When you are setting the interval on the hover-off, you are not setting itvl. itvl is actually an integer that acts as a reference to the interval. So the reference changes when you do window.setInterval(function(){scroll_()},3000);
without reffing it to anything.
Try this instead:
$('#carousel_ul li').hover(function() {
window.clearInterval(itvl);
}, function() {
itvl = window.setInterval(function(){scroll_()},3000);
});
OTHER TIPS
$('#carousel_ul li').hover(function() {
window.clearInterval(itvl);
}, function() {
itvl = window.setInterval(function(){scroll_()},3000);
});
You can use a boolean variable rather than clearInterval:
var scrolling= true;
window.setInterval(scroll_,3000);
function scroll_() {
if(scrolling) {
if ($('#carousel_ul li').length > 1) {
$("#right_scroll").click();
}
}
}
$('#carousel_ul li').hover(function() {
scrolling = false;
}, function() {
scrolling = true;
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow