Search code examples
javascriptjquerydelayfadein

Delay jQuery fadeIn due to unwanted behavior


How do I make my .right-menu DIV to fadein only after a couple of moments the mouse is hovering its parent .right-menu-background ? The thing is that when you move the cursor quickly in and out, .right-menu DIV is reappearing a lot of times after.

How do I delay animation for few ms?

Here's the code:

$(function(){
     $(".right-menu-background").hover(function(){
          $(this).find(".right-menu").fadeIn();
          }

,function(){
     $(this).find(".right-menu").fadeOut();
     }
);        
});

Solution

  • a easy fix is to use .stop()

    $(function () {
        $(".right-menu-background").hover(function () {
            $(this).find(".right-menu").stop(true, true).fadeIn();
        }, function () {
            $(this).find(".right-menu").stop(true, true).fadeOut();
        });
    });
    

    using timer

    $(function () {
        $(".right-menu-background").hover(function () {
            var el = $(this).find(".right-menu");
            var timer = setTimeout(function(){
                el.stop(true, true).fadeIn();
            }, 500);
    
            el.data('hovertimer', timer);
        }, function () {
            var el = $(this).find(".right-menu");
            clearTimeout(el.data('hovertimer'))
            el.stop(true, true).fadeOut();
        });
    });