Search code examples
javascriptfunctiondelay

I want to add a delay to my javascript function but dont know how


I am working with a menu and a multiple submenus. When you hover over a menu item, the submenu should appear, when you take your mouse off it should disappear. While this works i want the mouseout function to have a delay and I have tried multiple methods but i cant seem to get it to work.

PLEASE NOTE: The reason why I am using a mouseout function and not fadeToggle is because I have multiple items that can be hovered over. So if i move my mouse from menhuitem-1 to menuitem-2 i want that one to appear over it and vice versa.

This is my code (it works but i want a delay on mouseout):

$(function(){
 $("#menuitem-1").hover(function( e ){
  $("#subitem-1").stop().toggle().css('z-index', '1000');
 });
});
$(function(){
 $("#menuitem-1").mouseout(function( e ){
  $("#subitem-1").stop().css('z-index', '1');
 });
});

Solution

  • Maybe try something like this:

    $(function(){
        var elem = $("#subitem-1");
        var menuitem = $("#menuitem-1");
        var timeout;
        menuitem.hover(function( e ){
            clearTimeout(timeout);
            elem.stop().toggle().css('z-index', '1000');
        });
    
        menuitem.mouseout(function( e ){
            timeout = setTimeout(function(){
                elem.stop().css('z-index', '1');
            }, 3000);
        });
    });