Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If element has been 'mouseover'ed for 500ms, run function with jQuery

For the sanity of my users, I want a 'mouseover' event to run after the selector has been hovered for half a second rather than as soon as they hover it.

I first tried a setTimeout function but that runs however long the element has been hovered, I didn't think it through too much I guess. I've also spent a day (on and off) searching (and playing Pacman) ti no result, unless I'm searching for the wrong things.

I would like to keep this plugin-less if we can, purely for run speed & maintainability.

$("#mySelector").mouseover(function(){
    // Run after 500ms
    $(this).addClass("hasBeen500ms");
});

Let's see if we can crack this, I know it will have so many applications!

like image 848
PaulAdamDavis Avatar asked May 23 '10 14:05

PaulAdamDavis


1 Answers

Prevent from showing up if mouse is already out by the time the delay is expired, plus remove class on mouse out:

$("#mySelector").mouseenter(function() {
  var el = $(this);
  var timeoutId = setTimeout(function() {
    el.addClass("hasBeen500ms");
  }, 500);
  el.mouseleave(function() {
    clearTimeout(timeoutId);
    el.removeClass("hasBeen500ms");
  });
});
​
like image 168
serg Avatar answered Sep 27 '22 23:09

serg