Javascript Delay

I have an image on my site that is assigned a hquery hover action. But itโ€™s easy to accidentally hover your mouse over this area, and if you do this more than once, the guidance continues to appear, disappear, appear, etc., until it is shown and disappears once each time you cheat it . Is there a way to make the action fail if you donโ€™t bring a couple of seconds? I donโ€™t want to just postpone the action because it will happen for every hover anyway, I want to see if there is a way that the hover does not count if you are not in the image for a few seconds.

Script:

$("img.badge").hover( function() { $("h3.better").animate({"left": "125px"}, 1200); }, function() { $("h3.better").animate({"left": "-500px"}, 800); }); 
+8
javascript jquery hover delay
source share
3 answers

You can use setTimeout to trigger an action and bind a function that calls clearTimeout in the mouseout event:

 $('img.badge').hover(function(){ window.mytimeout = setTimeout(function(){ $("h3.better").animate({"left": "125px"}, 1200); }, 2000); }, function(){ clearTimeout(window.mytimeout); }); 

Or you can use a plugin for this, for example hoverintent .

+9
source share

Use .stop() before animation to undo the previous animation. I believe that this is what you are looking for and will solve your current problem.

 $("img.badge").hover( function() { $("h3.better").stop().animate({"left": "125px"}, 1200); }, function() { $("h3.better").stop().animate({"left": "-500px"}, 800); }); 
0
source share

You can use the timer to not trigger the hover action until you hover a certain amount of time like this, and then if the hover goes before the timer fires, you clear the timer, so nothing happens if you are just a short period of time:

 $("img.badge").hover(function() { var timer = $(this).data("hover"); // if no timer set, set one otherwise if timer is already set, do nothing if (!timer) { // set timer that will fire the hover action after 2 seconds timer = setTimeout(function() { $("h3.better").stop(true).animate({"left": "125px"}, 1200); $(this).data("hover", null); }, 2000); // save timer $(this).data("hover", timer); } }, function() { var timer = $(this).data("hover"); if (timer) { clearTimeout(timer); $(this).data("hover", null); } else { // probably would be better to make this an absolute position rather // than a relative position $("h3.better").stop(true).animate({"left": "-500px"}, 800); } }); 

Note. I also added .stop(true) to your animation so that animations never accumulate.

0
source share

All Articles