Yes, I know this question has been asked before, but I can't find an answer that works. This is an accepted answer from one of the other questions:
$('#element').hover(function()
{
$(this).data('timeout', window.setTimeout(function()
{
alert('hovered for 2 seconds');
}, 2000));
},
function()
{
clearTimeout($(this).data('timeout'));
alert('mouse left');
});
http://jsfiddle.net/nCcxt/
As you see it doesn't do what it's supposed to.
What I need is simple in theory but I can't get it to work - when a user hovers over a link for 2 seconds, a function is called. If the user moves the mouse away before 2 seconds pass, nothing happens.
HTML HTML Tag Reference ... The hover() method specifies two functions to run when the mouse pointer hovers over the selected elements. This method triggers both the mouseenter and mouseleave events. Note: If only one function is specified, it will be run for both the mouseenter and mouseleave events.
Another way to wait for a function to execute before continuing the execution in the asynchronous environment in JavaScript is to use async/wait.
Use async/await to Wait for a Function to Finish Before Continuing Execution. Another way to wait for a function to execute before continuing the execution in the asynchronous environment in JavaScript is to use async/wait.
Use promises to Wait for a Function to Finish in JavaScript A promise is an object representing the eventual fulfillment or failure of an asynchronous operation. We attach the fulfillment callback to the promise with one or more then statements, and when can call the error handler callback in the catch.
The code works perfectly fine. It only breaks due to the alert()
calls which causes the mouseout event to be triggered.
What do we learn from it? Do not use alert()
in combination with focus/hover/mousemove-related events.
By the way, there are already jQuery plugins available for what you want to do: http://cherne.net/brian/resources/jquery.hoverIntent.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With