user381800
user381800

Reputation:

jQuery pause function on hover?

I have a jQuery/JS function that is using setInterval to loop through some image slides I have. It just flips through every 5 seconds...

Now I want it to pause if my mouse is hovered over it. How do I go about doing that on the setInterval function?

var current = 1;

function autoAdvance() {
    if (current == -1) return false;

    jQuery('#slide_menu ul li a').eq(current % jQuery('#slide_menu ul li a').length).trigger('click', [true]);
    current++;
}

// The number of seconds that the slider will auto-advance in:
var changeEvery = jQuery(".interval").val();
if (changeEvery <= 0) {
    changeEvery = 10;
}
var itvl = setInterval(function () {
    autoAdvance()
}, changeEvery * 1000);

Upvotes: 4

Views: 12527

Answers (2)

Reid
Reid

Reputation: 19409

(function () {
    var imgs = $('#your_div img'), index = 0, interval,

        interval_function = function () {
            imgs.eq(index).hide();
            index = (index + 1) % imgs.length;
            imgs.eq(index).show();
        };

    imgs.eq(0).show();
    interval = setInterval(interval_function, 5000);

    $('#your_div').hover(function () {
        clearInterval(interval);
    }, function () {
        interval = setInterval(interval_function, 5000);
    });
}());

Example: http://jsfiddle.net/Zq7KB/3/

I reused some old code I wrote for a question the other day, but I figured it didn't matter that much. The trick is to store your interval in a variable that you keep in the background. Then, when you hover over the container, clear the interval. When you hover out of the container, re-set the interval. To get a better feel of how this works, change those 5000s to 1000s so it passes more quickly for testing.

Hope this helps.

Upvotes: 4

Jacob Relkin
Jacob Relkin

Reputation: 163238

Something like this would work assuming interval is defined in an outer scope:

$('.slideshow img').hover(function() {
  interval = clearInterval(interval);
}, function() {
  interval = setInterval(flip, 5000);
});

Upvotes: 4

Related Questions