user3043983
user3043983

Reputation: 61

How to make this script pause on hover?

I'm new to jQuery and I need a bit of help. I'm using this jQuery script as a testimonial rotator and it works like a charm but I just need to make one small tweak. I need it to be able to pause on hover and then restart when the mouse leaves the div. How can I do this?

This is the script I'm using:

function fadeMyContent() {
    $(".testimonial:first").fadeIn(1000).delay(3000).fadeOut(1000,
        function() {    
            $(this).appendTo($(this).parent());   
            fadeMyContent();    
        });
    }

    fadeMyContent();
});

Here is a JSFiddle.

Upvotes: 4

Views: 138

Answers (2)

Udit Bhardwaj
Udit Bhardwaj

Reputation: 1781

change the definition of fadeMyContent (also called as destroying function) on hovering on ul#testimonial-rotator and on hover-out change it to old definition again. I have used setTimeout in place of delay because delay is not cancellable.

$(document).ready(function () {
var fadeMyContent;
var t
fadeMyContent = function () {

    $(".rotate:first").fadeIn(1000)
    t = setTimeout(function () {
        $(".rotate:first").fadeOut(1000,

        function () {
            $(this).appendTo($(this).parent());
            fadeMyContent();
        });
    }, 3000)
}

var fadeMyContentDummy = function () {

    $(".rotate:first").fadeOut(1000,

    function () {
        $(this).appendTo($(this).parent());
        fadeMyContent()
    });
}


fadeMyContent();

$('#testimonial-rotator').hover(function (e)

{
    window.clearTimeout(t)
    $('.rotate:first').clearQueue()

    fadeMyContent = function () {

        return false;
    }

},

function (e)

{

    fadeMyContent = function () {

        $(".rotate:first").fadeIn(1000)
        t = setTimeout(function () {
            $(".rotate:first").fadeOut(1000,

            function () {
                $(this).appendTo($(this).parent());
                fadeMyContent();
            });
        }, 3000)
    }

    fadeMyContentDummy()

})


});

DEMO

Upvotes: 1

FluffyJack
FluffyJack

Reputation: 1732

There is a plugin that will provide all the functionality you need and be more reliable called jQuery Cycle 2.

It provides a 'pause-on-hover' option when initialising it.

Upvotes: 1

Related Questions