I have created a carousel that slides every 5 seconds automatically (as well as having manual buttons to move slides). I want to be able to pause the scrolling when the mouse is hovered over a slide, and resume when the mouse is no longer hovered.

So far my script will do all of the above.
However it won't start on page load, you have to hover over and then un-hover for it to start.

Here is my script:

jQuery('#viewport').hover(function () {
    window.clearInterval(timer);
}, function () {
    timer = window.setInterval(function () {
        jQuery('#next').trigger('click');
    }, 1000);
});

What can I do to get this to start sliding straight away?

有帮助吗?

解决方案

jQuery('#viewport').on({
    mouseenter: function() {
        clearInterval( $(this).data('timer') );
    },
    mouseleave: function() {
        $(this).data('timer', setInterval(function () {
            jQuery('#next').trigger('click');
        }, 1000));
    }
}).trigger('mouseleave');

其他提示

function nextSlide () {
   jQuery('#next').trigger('click');
} 

jQuery('#viewport').hover(function() {
  window.clearInterval(timer);    
}, function() {
  timer = window.setInterval(nextSlide, 1000);
});

nextSlide();

Wrap everything inside

$(document).ready(function()
{
    // Your code there.
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top