jquery using multiple setTimeouts

javascript, jquery, timeout

Solution

You can maintain an array of timers like

var timer = [];


$('.label').mouseenter(function(){

    clearTimeout(timer[$(this).index()]);

    $('#' + this.id + ' div').slideDown('slow');

});


$('.label').mouseleave(function(){

    var temp = $('#' + this.id + ' div');

    timer[$(this).index()] = setTimeout(function() { 
        temp.stop().slideUp('slow');
    }, 2000);

}); 

You can also achieve this with a more clear syntax using `.hover` like

var timer = [];

$('.label').hover(function(){

    clearTimeout(timer[$(this).index()]);

    $('#' + this.id + ' div').slideDown('slow');

},function(){
    var temp = $('#' + this.id + ' div');

    timer[$(this).index()] = setTimeout(function() { 
        temp.stop().slideUp('slow');
    }, 2000);

});

Problem

I am currently creating a site with some dynamic content, so that whenever a user hovers over a label, the label expands to show more information, then after a specific time the label will collapse again, unless the user hovers over the label again in which case the Timeout will reset. I have developed the code to do this for 1 label, but I would to develop it now to do it for multiple labels. The problem I'm having though is that I am defining the variable for the timer globally so it can be used for both events, this won't work when I have multiple labels though. I can't think how I can achieve this for multiple labels, does anyone have any idea how I can do this? Here is my code so far... ``` var timer; $('.label').mouseenter(function(){ clearTimeout(timer); $('#' + this.id + ' div').slideDown('slow'); }); $('.label').mouseleave(function(){ var temp = $('#' + this.id + ' div'); timer = setTimeout(function() { temp.stop().slideUp('slow'); }, 2000); }); ``` Thanks in advance for any help.

Original source