Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add delay to jquery mouseover? [duplicate]

Tags:

I have a bunch of images on one page and I am using the following to trigger an event:

$('.img').on('mouseover', function() {
 //do something

});

Is there some way to add a delay such that if a user hovers for maybe 1 second, then it does "//do something" or actually triggers the "mouseover" event?

like image 902
Rolando Avatar asked Mar 22 '13 17:03

Rolando


3 Answers

You can use setTimeout

var delay=1000, setTimeoutConst;
$('.img').on('hover', function() {
  setTimeoutConst = setTimeout(function() {
    // do something
  }, delay);
}, function() {
  clearTimeout(setTimeoutConst);
});
like image 200
Anoop Avatar answered Sep 22 '22 20:09

Anoop


You could do that using a setTimeout along with a clearTimeout if the user leaves too soon:

var timer;
var delay = 1000;

$('#element').hover(function() {
    // on mouse in, start a timeout

    timer = setTimeout(function() {
        // do your stuff here
    }, delay);
}, function() {
    // on mouse out, cancel the timer
    clearTimeout(timer);
});
like image 30
xbonez Avatar answered Sep 24 '22 20:09

xbonez


Use a timer and clear it when they mouseout incase they leave within 1000ms

var timer;

$('.img').on({
    'mouseover': function () {
        timer = setTimeout(function () {
            // do stuff
        }, 1000);
    },
    'mouseout' : function () {
        clearTimeout(timer);
    }
});
like image 43
Mark Pieszak - Trilon.io Avatar answered Sep 26 '22 20:09

Mark Pieszak - Trilon.io