user1015104
user1015104

Reputation:

jquery an event if the cursor was on the element for some time

I have a div and when I point the mouse on it I want to fire an event. But I want to fire it only if the cursor was on the event for some amount of time.

Any suggestions how to do this?

Upvotes: 1

Views: 145

Answers (2)

Salvador Dali
Salvador Dali

Reputation: 222869

Here is an example:

$('#yourElement').on({
        mouseenter: function (){
            clearTimeout(testTimeout);       // [1]
            testTimeout = setTimeout(function(){  // [2]
                ...
            }, numberOfMiliseconds);
        },
        mouseleave: function () { //[3]
            clearTimeout(testTimeout);
        }
    }, '.whereIsYourElement');

[1] when mouse is entering the element, it removes the previous timeout and raise it [2] one more time. When the mouse is leaving the area [3] it also deletes timeout. This gives the desirable effect, that the timeout executes only if the mouse entered and stayed in the element for some time.

Upvotes: 0

Wesley Petrowski
Wesley Petrowski

Reputation: 1131

  1. Add a mouseover event that sets a timer.
  2. Add a mouseout event that cancels the timer.
  3. When the timer elapses, do the stuff you want to do.

Upvotes: 1

Related Questions