开发者

Adding delay to mouse out function

开发者 https://www.devze.com 2022-12-29 22:57 出处:网络
I have one drop down menu, <ul> <li><a>link 1</a> <ul><li><a>link 1</a></li></ul>

I have one drop down menu,

<ul>
<li><a>link 1</a>
<ul><li><a>link 1</a></li></ul>
</li>
</ul>

I am using the following JS to u开发者_运维知识库se hover and show child menus.

I want to add delay to the mouse out function (when the class of the LI removed) about 500ms,

 $('li').hover(function(){
    $(this).addClass('over');
    }, function(){
    $(this).removeClass('over');
  });

Please do needful in this.

thanks in advance


You can do something like this:

$('li').hover(function(){
  var timer = $(this).data('timer');
  if(timer) clearTimeout(timer);
  $(this).addClass('over');
}, function(){
  var li = $(this);
  li.data('timer', setTimeout(function(){ li.removeClass('over'); }, 500));
});

This clears any timeout when hovering over it (in case you hover, leave, hover back you need to check this) and sets a 500ms delay when leaving the hover, storing the timeout ID on the li itself using .data().


$('li').hover(function(){
    $(this).addClass('over');
    }, function(){
    setTimeout(function(){$(this).removeClass('over')}, 500);
  });
0

精彩评论

暂无评论...
验证码 换一张
取 消