Reputation: 2391
I am trying to achieve a time delay during a hover effect for a dropdown menu. I am trying to use the setTimeout and the dropdown do work correctly on hover, but I don't get the delay. It happens just instantaneously. Below is my code:
$(document).ready(function(){
$("li.dropdown-hover").hover(hoverIn, hoverOut);
});
function hoverIn(){
setTimeout(func1(this), 3000);
}
function hoverOut(){
setTimeout(func2(this), 1000);
}
function func1(element) {
$(element).find(".dropdown-menu-hover").css("display", "block");
}
function func2(element) {
$(element).find(".dropdown-menu-hover").css("display", "none");
}
I am pretty new to jQuery and for some reason, I don't wish to use any external plugin such as http://cherne.net/brian/resources/jquery.hoverIntent.html which is suggested in many similar questions. Can someone tell me what is going wrong here?
Upvotes: 1
Views: 63
Reputation: 32511
When you write setTimeout(func1(this), 3000);
, you're invoking the func1
function immediately. It's the same thing as this:
func1(this);
setTimeout(undefined, 3000);
Instead, you want to pass setTimeout
a new function which will run after the allotted time.
var self = this;
setTimeout(function() {
func1(self);
}, 3000);
Or you can pass this
as an extra parameter as Richard B shows.
Upvotes: 3
Reputation: 318
You could use jQuery's default function .delay
like this:
$('.a').hover(function () {
$('.b').delay(2000).fadeIn(200);
});
jsFiddle: https://jsfiddle.net/sukritchhabra/upkgtLyn/1
Upvotes: 1
Reputation: 2767
I believe you have to pass parameters to the function as follows:
setTimeout(func1, 3000,this);
as opposed to
setTimeout(func1(this), 3000);
Upvotes: 0