If the item was "hover over the mouse" for 500 ms, run the function using jQuery

For the convenience of my users, I want the mouseover event to fire after the selector has been hung for half a second, and not immediately as soon as it hovers it.

At first I tried the setTimeout function, but it works, although the element was visible, I did not think it was too much, I think. I also spent the day (on and off), looking for (and playing Pacman) ti no result unless I looked for the wrong things.

I would like to keep this plugin, if possible, purely for speed of execution and maintainability.

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

Let's see if we can hack it, I know that he will have so many applications!

+5
source share
7 answers

Prevent display if the mouse has already left by the time the delay expires, and also delete the class using the mouse:

$("#mySelector").mouseenter(function() {
  var el = $(this);
  var timeoutId = setTimeout(function() {
    el.addClass("hasBeen500ms");
  }, 500);
  el.mouseleave(function() {
    clearTimeout(timeoutId);
    el.removeClass("hasBeen500ms");
  });
});
+14
source

.delay()did not work, because .addClass()it is not part of the animation queue, so instead I decided to animate something null (the decision was made visibility:visible, since you will not hover over an invisible element) and then start adding the hover class to the callback function:

$('#mySelector').mouseenter(function(){
    $(this).animate({'visibility':'visible'},500,'swing',function(){
        $(this).addClass('hoverIntent');
    })
});

$('#mySelector').mouseleave(function(){
    $(this).removeClass('hoverIntent').stop().clearQueue();
});

In the class, the mouseleave is deleted, and the animation queue is stopped and cleared if it is up to 500 ms. You can add the same functionality to mouseleave if you need a delay before disconnecting.

+1
source

- , , 500 :

var timer;

$('#mySelector').mouseover(function() {
    timer = setTimeout( function() {$(this).addClass('hasBeen500ms');}, 500);
});

$('#mySelector').mouseout(function() {
    clearTimeout(timer);
});
+1
+1

SO setTimeout.

0

-

, :

var isMouseOver=false;

$("#mySelector").mouseover(function(){
   isMouseOver=true;//set variable to gtrue
   setTimeout(function() {
                 if(isMouseOver){
                      $(this).addClass("hasBeen500ms");
                 }
              }, 500);
});

mouseout, , - 500 .

$("#mySelector").mouseout(function(){
   isMouseOver=false;//set variable to false
});

, !

0

, - . Google,

google.maps.event.addListener(marker, 'mouseover', function(){
  this.timeout = setTimeout(markerClick.bind(this, false), 500)
  google.maps.event.addListener(this, 'mouseout', function(){
    if(this.timeout){
      clearTimeout(this.timeout)
      delete this.timeout
    }
    google.maps.event.clearListeners(this, 'mouseout');
  }.bind(this))
}.bind(marker))
0

All Articles