Frank Parent
Frank Parent

Reputation: 2164

Using setInterval in jQuery's live events mouseOver/mouseOut

Hey guys!
I'm trying to start a timer when a user mouseOver an element and stop it on the mouseOut. The elements are created dynamically, which is the reason the use of the live method.

So my timer starts correctly, but I can't stop it! What's wrong?

$elems.live('mouseover mouseout', function(event) {
        var self = $(this), i = 0;

        if (event.type == 'mouseover') {
            var timer = setInterval(function() {
                // change the src of the current element for an element of an array of src, much like in a slideshow
                self.attr('src', tabSrc[i]);
                i === 2 ? i = 0 : i++;
            }, 1000);
        }
        // Handle the mouseOut
        else {
            // stop the timer <------ when I mouseOut the element, this doesn't seems to work...
            clearInterval(timer);
        }
    });

Upvotes: 0

Views: 2450

Answers (1)

Nick Craver
Nick Craver

Reputation: 630627

Your timer variable isn't scope correctly, it needs to be outside the handler, like this:

var timer;
$elems.live('mouseover mouseout', function(event) {
    var self = $(this), i = 0;

    if (event.type == 'mouseover') {
        timer = setInterval(function() {
            self.attr('src', tabSrc[i]);
            i === 2 ? i = 0 : i++;
        }, 1000);
    }
    else {
        clearInterval(timer);
    }
});

Or, alternatively use $.data() to store an interval per element, like this:

$elems.live('mouseover', function() {
    var self = $(this), i = 0;
    $.data(this, 'timer', setInterval(function() {
       self.attr('src', tabSrc[i]);
       i === 2 ? i = 0 : i++;
    }, 1000));
}).live('mouseout', function() {
   clearInterval($.data(this, 'timer'));
});

Upvotes: 5

Related Questions