I have some code that adds mouseover events and mouseout events to all 'a' tags on a page. I'd like it so that the mouseout starts a 5 second timer after which time it calls a function. However, if a new mouseover event fires, it should cancel any existing timers. The code I'm using follows. The setTimeout() is working fine, but it seems like the clearTimeout() isn't referencing the right timeoutID, even though I declared it globally. Any suggestions?
var timeoutID;
function addMouseoverEvent() {
$('a').each(function(index) {
$(this).mouseover(function() {
clearTimeout(timeoutID);
// do stuff
})
});
}
function addMouseoutEvent() {
$('a').each(function(index) {
$(this).mouseout(function() {
timeoutID = setTimeout(function() {
// do stuff
}, 5000);
})
});
}
$(window).load(function() {
addMouseoverEvent();
addMouseoutEvent();
});
I should clarify that there should really only ever be one active timer. That's why I wanted it to be global. If a mouseover event occurs no timers should remain. And if a mouseout event occurs only one timer should be active - the one triggered by the last mouseout event.