Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make function execute after user hovers over link for 2 seconds

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.

like image 633
sveti petar Avatar asked Jun 16 '12 11:06

sveti petar


People also ask

How does hover work in HTML?

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.

How to wait for a function to execute in the asynchronous environment?

Another way to wait for a function to execute before continuing the execution in the asynchronous environment in JavaScript is to use async/wait.

How to wait for a function to finish before continuing execution?

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.

How do you wait for a function to finish in JavaScript?

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.


1 Answers

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

like image 181
ThiefMaster Avatar answered Oct 20 '22 08:10

ThiefMaster