Creating logic with jQuery depending on where the user hovers their mouse
I have a list item that when a user hover theirs mouse over it, a div on the page animates. The problem I'm having is what happens next. When the user moves their mouse off the original list item, if they move it over the div that originally animated, I have the logic working from there no problem. The problem is what happens if the开发者_如何学C user hovers off the list item and does not hover over the animated div. I'm trying to create a function that accounts for this later situation. If the user hovers off the list item (li.solutions) and they do NOT hover over the animated div that just showed up, the animated div hides again.
I've posted the basic code on jsfiddle: http://jsfiddle.net/9bE2p/
I could imagine that you want the div
shown when li
is hovered, and when the user hovers away from both the div
and the li
, the div
must be hidden.
If so, than this might be what you are looking for?
$(document).ready(function(){
// hide nav_top_dropdown first
$('.nav_top_dropdown').hide();
// set hover functionality, also on the hidden dropdown
$('.solutions, .nav_top_dropdown').hover(function(){
$('.nav_top_dropdown').show();
}, function(){
// hovering off situation
$('.nav_top_dropdown').hide();
});
});
I think the following is the sort of thing you want. Basically it starts the hide action when you leave the menu, but delays it to provide a chance to cancel, if e.g. the user moves the cursor onto the dropdown. If they do, the hide is reinstated when they move off the dropdown.
var timerId;
function maybeHideDropdown() {
function hideDropdown() {
$(this).removeClass('nav_down').animate({'top': '-120px'}, 1000);
}
timerId = setTimeout(hideDropdown, 200);
}
function cancelHideDropdown() {
clearTimeout(timerId);
}
$('.solutions').hover(
function () {
cancelHideDropdown(); // in case they move from dropdown back to menu
$('.nav_top_dropdown').animate({'top': '+60px'}, 1000).addClass('nav_down');
},
function () {
maybeHideDropdown();
}
);
$('.nav_top_dropdown').hover (
function () {
cancelHideDropdown();
$(this).addClass('nav_down');
},
function () {
maybeHideDropdown();
}
);
精彩评论