Search code examples
javascriptjquerysliderslideshowmousehover

Pause slide show on hover


I have the following script to run a slideshow, that works just fine.

jQuery(document).ready(function ($) {


setInterval(function () {
    moveRight();
}, 5000);


var slideCount = $('#slider ul li').length;
var slideWidth = $('#slider ul li').width();
var slideHeight = $('#slider ul li').height();
var sliderUlWidth = slideCount * slideWidth;

$('#slider').css({ width: slideWidth, height: slideHeight });

$('#slider ul').css({ width: sliderUlWidth, marginLeft: - slideWidth });

$('#slider ul li:last-child').prependTo('#slider ul');

function moveLeft() {
    $('#slider ul').animate({
        left: + slideWidth
    }, 500, function () {
        $('#slider ul li:last-child').prependTo('#slider ul');
        $('#slider ul').css('left', '');
    });
};

function moveRight() {
    $('#slider ul').animate({
        left: - slideWidth
    }, 500, function () {
        $('#slider ul li:first-child').appendTo('#slider ul');
        $('#slider ul').css('left', '');
    });
};

$('a.control_prev').click(function () {
    moveLeft();
});

$('a.control_next').click(function () {
     moveRight();
});
});

But I want it to pause on mouse hover, and I've tried a few other suggestions I found here on SO (including the one below), but couldn't make any of them work with the code I have. Any ideas? Thanks.

$("#slider ul").mouseover(function() {
$("#slider ul").trigger('pause', true);
});

Solution

  • You can use .stop(), clearInterval()

    // define reference to `setInterval()` call
    var interval = setInterval(function () {
        moveRight();
    }, 5000);
    
    // stop animations, clear `interval`
    $("#slider ul").mouseover(function() {
      $(this).stop();
      clearInterval(interval);
    });