Search code examples
javascriptjquerymouseentermouseleave

Mouseleave does not work with .each and delay?


I have written some code to change the colour of each letter inside an a tag and show a pop up when you hover the link.

The mouseenter function works fine but when you hover off the link I would like to do the reverse of the original change ( so change back to the origional colour ).

I take the delay out of the leave function it works but the effect is not as nice. I am confused as to why this works on the enter but not on the leave?

Another thing to mention is when it does change colour back to the grey the mouseenter function does not work again, which is kind of annoying.

Here is a link to the site so you can see what I am talking about and the link is the one at the bottom that says "Touch Marketing"

http://dev.touch-akl.com/colin/

Any help please?

My jQuery looks like this

$('#copyright a').mouseenter(function(){

    var $letters = $(this).find('span'),
    $sayhi = $(this).find('img'),
    delay = 0;

    $sayhi.animate({top:-30, 'opacity':1}, 500, "easeInOutExpo");

    $letters.each(function(){

        $(this).delay(delay).queue(function(){
            $(this).css({'color':'#333'});
        });

        delay+=35;      

    }); // end each

}).mouseleave(function(){

    var $letters = $(this).find('span'),
    delay = 0;

    $letters.each(function(){

        $(this).delay(delay).queue(function(){
            $(this).css({'color':'#333'});
        }); 

        delay+=35;      

    });

}); // end leave

Solution

  • jQuery .queue() is complicated to use correctly so unless you need to interact with other things in the jQuery animation queue, it is often much, much simpler to just use setTimeout() like this. You also should make delay a local variable so it isn't an implicit global variable.

    }).mouseleave(function(){
        var delay = 0;
        $(this).find('span').each(function(){
            var item = $(this);
    
            setTimeout(function(){
                item.css({'color':'#333'});
            }, delay); 
    
            delay+=35;      
        });
    }); // end leave