1

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks ! I think it worked for me. I still need to test it a little bit more. I tried this earlier but it did not work for me. May be I was doing something silly or stupid. You put it perfectly.
2
var timer;

$("element").mouseenter(function(){
    timer = setTimeout(function(){
        //show help box
    }, 500);
});

$("element").mouseleave(funciton(){
    clearTimeout(timer);
});

2 Comments

Your "timer" variable is local to the "mouseover" handler, and therefore it won't be available to the "mouseout" handler.
and there is a setTimeout being cleared by a clearInterval - is that allowed?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.