Search code examples
jqueryhoversetintervalfadeclearinterval

JQuery setInterval with pause on hover


I am trying to get multiple divs to fade in and fade out. Then on hover, pause the animation. Then on hover out, continue the animation. Right now I've gotten this far, the divs fade in and out correctly, and on hover it stops. But when I hover out, the animation doesn't start again. Any suggestions as to what I'm doing wrong?

var timer;
$(document).ready(function(){
    $(function startTimer(){
        $('#quotes .textItem:gt(0)').hide();
        timer = setInterval(function(){$('#quotes > :first-child').fadeOut().next('div').fadeIn().end().appendTo('#quotes');}, 1000);
    });

    $('#quotes').hover(function (ev) {
        clearInterval(timer);
    }, function (ev) {
        startTimer();
    });
}); 

Here is my jfiddle:


Solution

  • try this

    var timer;
    $(document).ready(function(){
        timer = function(){$('#quotes > :first-child').fadeOut().next('div').fadeIn().end().appendTo('#quotes');};
        $('#quotes .textItem:gt(0)').hide();
        var interval = setInterval(timer , 2000);
    $('#quotes').hover(function (ev) {
        clearInterval(interval);
    }, function (ev) {
        interval = setInterval(timer , 2000);
    });
    }); 
    

    DEMO HERE