Reputation:
I have this code that makes menu items slide down and up. I want to add a timer so there is a delay in the slide down then back up.
$(function () {
$("#menu").find("li").each(function () {
if ($(this).find("ul").length > 0) {
$(this).mouseenter(function () {
$(this).find("ul").stop(true, true).slideDown();
});
$(this).mouseleave(function () {
$(this).find("ul").stop(true, true).slideUp();
});
}
});
});
Upvotes: 2
Views: 196
Reputation: 206669
A smart approach would be to add a hover intent to wait before triggering mouseleave:
$("#menu").find("li:has(ul)").on('mouseenter mouseleave',function( e ){
var $UL = $(this).find('ul');
if(e.type==='mouseenter'){
clearTimeout( $(this).data('wait') );
$UL.stop(1,1).slideDown();
}else{
$(this).data('wait', setTimeout(function(){
$UL.stop().slideUp();
},180) );
}
});
if ($(this).find("ul").length > 0) {
just use: ("li:has(ul)")
li
elements that has ul
as children.e
for the mouseenter mouseleave
.e
event == mouseenter
..... else
is mouseleave
.data
attribute called 'wait' and slideDown the children ul
li
element to reach the 'distant' ul
we have to cross over a white space (demo) that will usually trigger immediately the 'slideUp()', but we set a timeout counter inside that li
's data attribute that will wait ~180ms before running.ul
element - beeing a children of the timeouted 'li' we clear the timeout (step 1) 'retaining' the mouseenter state.use ~180ms or how much you think is needed to reach with the mouse the 'distant' UL element
Upvotes: 0
Reputation: 276596
It appears like you're writing javascript with jQuery
jQuery has a built in .delay
function for animation queues.
In your example, delaying the slidedown animation by 300 ms would look like
$(this).find("ul").stop(true, true).delay(300).slideDown();
See jQuery's delay
Upvotes: 4