I am needing to add a delay to the mouseover event of my dropdown menu so that if someone mouses over the menu going to another link on page the menu will not drop down instantl
You can add a setTimeout()
to delay the show()
, and on hover out clear the timeout so that if the user moves the mouse out before the delay is up it will be cancelled. And you can encapsulate that in your own jQuery plugin:
jQuery.fn.hoverWithDelay = function(inCallback,outCallback,delay) {
this.each(function(i,el) {
var timer;
$(this).hover(function(){
timer = setTimeout(function(){
timer = null;
inCallback.call(el);
}, delay);
},function() {
if (timer) {
clearTimeout(timer);
timer = null;
} else
outCallback.call(el);
});
});
};
Which you can use like this:
$('ul.top-level li').hoverWithDelay(function() {
$(this).find('ul').show();
}, function() {
$(this).find('ul').fadeOut('fast', closeMenuIfOut);
}, 500);
I cobbled that plugin together in a hurry so I'm sure it could be improved, but it seems to work in this updated version of your demo: http://jsfiddle.net/NPVVQ/3/
As far as explaining how my code works: the .each()
loops through all the elements in the jQuery object that the function is called on. For each element a hover handler is created that uses setTimeout()
to delay calling the callback function provided - if the mouseleave occurs before the time is up this timeout is cleared so that the inCallback
is not called. The .call()
method is used on inCallback
and outCallback
to set the right value for this
.