I'm using the below jQuery/javascript to control the hover functionality of a menu. When an "item-wrapper" item is hovered over,开发者_如何学运维 it display a tooltip submenu.
I wish to add two pieces of functionality to this code:
1) For the Tooltip to only appear after 500milliseconds of hovering over a menu item
2) For the user to be able to move off the tooltip and have it stay visible for about 1 second (thus giving them the option to move back over it before it disappears)
$(".item-wrapper").hover(function() {
$('#' + $(this).attr("rel") + '-tip').fadeIn("fast").show(); //add 'show()'' for IE
},
function() {//hide tooltip when the mouse moves off of the element
$('#' + $(this).attr("rel") + '-tip').hide();
});
All help greatly appreciated
You can use setTimeout
to delay the call. The tricky part is making sure to clear the timeouts correctly if the user re-hovers over the element, or hovers over a different one.
var timeouts = {};
$(".item-wrapper").hover(function() {
var rel = $(this).attr("rel");
var el = $('#' + rel + '-tip');
if (timeouts[rel]) clearTimeout(timeouts[rel]);
timeouts[rel] = setTimeout(function () { el.fadeIn("fast").show(); }, 500);
},
function() {
var rel = $(this).attr("rel");
var el = $('#' + rel + '-tip');
if (timeouts[rel]) clearTimeout(timeouts[rel]);
timeouts[rel] = setTimeout(function () { el.hide() }, 1000);
});
You may want to look into the hoverIntent plugin. Here's the short description:
instead of immediately calling the onMouseOver function, it waits until the user's mouse slows down enough before making the call
You can add the 500ms delay before showing the tooltip, but it's not necessary if you're just trying to prevent accidental mouse over. Here's how you may implement it.
$(".item-wrapper").hoverIntent({
over: function() { $('#' + $(this).attr("rel") + '-tip').delay(500).fadeIn("fast").show(); },
timeout: 1000, // number = milliseconds delay before onMouseOut
out: function() { $('#' + $(this).attr("rel") + '-tip').hide(); }
});
Add .delay(500) for the delay before .fadiIn,
Add another delay at the start of the mouseleave function.
How about use jquery delay for the mouseleave, so change it to:
function() {//hide tooltip when the mouse moves off of the element
$('#' + $(this).attr("rel") + '-tip').delay(500).hide();
});
to delay the hover event is a little more complicated, you need to keep a timer. Something like this:
$(function() {
var timer;
$(".item-wrapper").hover(function() {
if (timer)
{
clearTimeout(timer);
timer=null;
}
timer = setTimeout(function() {
$('#' + $(this).attr("rel") + '-tip').fadeIn("fast").show()
},500);
});
精彩评论