Reputation: 963
I am trying to set a delay before a help tip is shown on hover. However, the issue I am facing is that once the user's mouse touches the HTML element and quickly moves over, it still shows the help tip after 500ms is over. I only want the hover tip to be shown if the mouse hovers over for 500ms. If it leaves the area before 500ms, then it should not show the hover tip. Can you please help. Here is the code snippet. Please not that I know about existing plug-ins like hoverIntent etc but since I do quite a bit of custom things within my funciton, I would like t avoid using the plug-in and simply tweak my home grown solution. Thanks in advance for your suggestion.
Here is the code snippet
function displayTip(displayText, displayElement)
{
// some sanity check code here
setTimeout(function() {introduceDelay(displayText, displayElement) } ,500);
}
What I am trying to achieve is that if the user's mouse does not hover over the given html element for 500ms then the funciton call to introduceDelay is not made at all.
Upvotes: 1
Views: 827
Reputation: 305
var timer;
$("element").mouseenter(function(){
timer = setTimeout(function(){
//show help box
}, 500);
});
$("element").mouseleave(funciton(){
clearTimeout(timer);
});
Upvotes: 2
Reputation: 413702
Save the return value from setTimeout()
and then, in a "mouseleave" handler, clear it with clearTimeout
.
var timer;
function displayTip(displayText, displayElement)
{
// some sanity check code here
timer = setTimeout(function() {introduceDelay(displayText, displayElement) } ,500);
}
// ...
$('whatever').mouseleave(function() {
clearTimeout(timer);
});
You don't really have to worry about checking how long it's been; nothing bad happens if you call clearTimeout()
with a timer id that's already fired.
Upvotes: 3