Search code examples
jquerytogglesettimeoutfade

setTimeout on toggle in jQuery


My menu displays an icon and some text when hovering over the menu items. Unfortunately, when hovering from the top to the bottom (and back), the fade animation makes all the images and text go crossfading into each other, which isn't looking nice.

I'm looking for a way to put a setTimeout on the toggle so the icons and the texts only appear when the user hovers over a menu item for more than 1 second. If the user hovers quickly over the menu items, the icons and the texts won't display.

This is the jQuery I have now:

$('.button').hover(function () {
 var id = $(this).attr('id').substr(4);
 $('.content').not('#photo' + id).fadeOut();
 $('.text').not('#info' + id).fadeOut();

 $('#photo' + id).fadeToggle();
 $('#info' + id).fadeToggle();
});


$('.button').mouseout(function () {
    $('.content').fadeOut();
    $('.text').fadeOut();
});

I've made a jsfiddle with a live example: http://jsfiddle.net/MaxdeMooij/9ozqgLwq/ There are some topics about setTimeout on slidetoggles, but I can't integrate those sollutions in my code. Can anyone help me? It'd be great.

Thanks for helping out!


Solution

  • Here is another solution using timers. This one keeps the fadeout in play.

    var timerHandle = null;
    $('.button').hover(function() {
        if (timerHandle != null) {
            clearTimeout(timerHandle);
            timerHandle = null;
        }
        timerHandle = setTimeout($.proxy(function() {
            var id = $(this).attr('id').substr(4);
            $('.content').not('#photo'+id).fadeOut();
            $('.text').not('#info'+id).fadeOut();
    
            $('#photo'+id).fadeToggle();
            $('#info'+id).fadeToggle();
        }, this), 500);
    });
    
    $('.button').mouseout(function(){
        $('.content').fadeOut();
        $('.text').fadeOut();
        if (timerHandle != null) {
            clearTimeout(timerHandle);
            timerHandle = null;
        }
    });
    

    A jsFiddle has been provided.