Question

I have a rotating slider on a website that I am working on.

the slider automatically scrolls when the page is loaded, and is supposed to stop when it is moused over, and then start again when the mouse leaves.

I have the stopping of the slider working, but when i mouse out, the slider starts up again, but twice as fast, causing the slider to show no content.

Is there some reason why my clear interval is not working correctly? how can i get the slider to stop and start without it changing speed and messing up?

     rotateSwitch: function() {  
       var myTimer=setInterval(function() { this.autoRotate(); }.bind(this), 5000);
       $('.hero img').hover(
         function() {
         window.clearInterval(myTimer)},
         function() {
         this.rotateSwitch();}.bind(this));
    },       
Was it helpful?

Solution

On every mouseleave you bind the function again by calling this.rotateSwitch(). Instead, only start the interval again:

rotateSwitch: function() {  
    var myTimer,
        that = this;
    function start() {
        myTimer = setInterval(that.autoRotate.bind(that), 5000);
    }
    function stop() {
        clearInterval(myTimer);
    }
    $('.hero img').hover(stop, start);
    start();
},

If that function is called multiple times, you might want to restrict your .hero img selector to a specific context as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top