0

Using jQuery to hide a sub-menu on mouseleave, everything works fine, but when I try to use setTimeout the function doesn't work.

This is my code without setTimeout

$( "li.menu-item" ).hover(function() {  // mouse enter
  $( this ).find( ".sub-menu" ).show(); // display child
}, function(){ // mouse leave
  $( this ).find( ".sub-menu" ).hide(); 
});

And with setTimeout:

$( "li.menu-item" ).hover(function() {  // mouse enter
  $( this ).find( ".sub-menu" ).show(); // display child
}, function(){ // mouse leave
  setTimeout(function () {
    $( this ).find( ".sub-menu" ).hide();
  }, 2000);            
});

The setTimeout function is working, if I insert an alert inside, the execution is with 2 seconds delay.

Thank You.

Shiladitya
  • 12,003
  • 15
  • 25
  • 38
eifersucht
  • 661
  • 8
  • 26

2 Answers2

1

I think the problem that $(this) will not read inside setTimeout()

$( "li.menu-item" ).hover(function() {  // mouse enter
  $( this ).find( ".sub-menu" ).show(); // display child
}, function(){ // mouse leave
  var ThisIt = $(this);    
  setTimeout(function () {
    ThisIt.find( ".sub-menu" ).hide();
  }, 2000);
});
Shiladitya
  • 12,003
  • 15
  • 25
  • 38
Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28
0

Within setTimeout this has a different context, so you cannot target on "sub-menu". Keep a reference of this before setTimeout and use that to reference "sub-menu" inside setTimeout.

koninos
  • 4,969
  • 5
  • 28
  • 47