Dawn
Dawn

Reputation: 175

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:

Upvotes: 0

Views: 1930

Answers (2)

guest271314
guest271314

Reputation: 1

Try substituting calling startTimer() following $('#quotes .textItem:gt(0)').hide(); for calling startTimer() as argument to jQuery() call.

var timer;
$(document).ready(function () {

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

jsfiddle http://jsfiddle.net/cc1bewvk/6/

Upvotes: 0

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

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

Upvotes: 1

Related Questions