You're using the selector in a wrong way. $('sub')
will look for a tag named sub, but you want to find an element with class sub, you should be using $('.sub')
.
This alone will not fix your issue. Try following code
$('.mainnav > li').hover(
function () {
$(this).find('.sub').fadeIn(300);
},
function () {
var sub = $(this).find('.sub');
setTimeout(function () {
sub.fadeOut(300);
}, 2000)
}
);
And you don't need a separate mouseout event handler for the .mainnav
. The second argument of jquery hover
is a mouseout handler.
And for sake of describing my answer, var sub = $(this).find('.sub');
is created to save a reference to the hovered .sub
and pass it to the function because this
inside an anonymous function will refer to the window
object
Update
Following code is to prevent the fadeout+fadein if the user moves the mouse away from menu and hovers it again before the menu has fadedout completely.
$('.mainnav > li').hover(
function () {
//this clears the timeout that is going to cause a fadeout
window.clearTimeout(window.menufade);
$(this).find('.sub').fadeIn(300);
},
function () {
var sub = $(this).find('.sub');
//this clears the timeout that is going to cause a fadeout, not necessary here I think, but i'll let it be :)
window.clearTimeout(window.menufade);
window.menufade = setTimeout(function () {
sub.fadeOut(300);
}, 2000)
}
);