Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delay Javascript hover action

I have an image on my site that has a jquery hover action assigned to it. But it's easy to accidentally mouse over that area, and if you do it more than once, the hover keeps appearing, disappearing, appearing, etc, until it's shown and disappeared once for every time you moused over it. Is there a way to make it so the action doesn't fire unless you hover for a few seconds? I don't want to just delay the action, because it would still happen for every mouseover, I want to see if there's a way the mouseover doesn't count unless you're on the image for a few seconds.

Script so far:

$("img.badge").hover(
function() {
  $("h3.better").animate({"left": "125px"}, 1200);
},
function() {
  $("h3.better").animate({"left": "-500px"}, 800);
});
like image 514
Molly Campbell Avatar asked Feb 11 '13 18:02

Molly Campbell


2 Answers

You could use setTimeout to launch the action and bind a function calling clearTimeout on the mouseout event :

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

Or you could use a plugin for that, like hoverintent.

like image 124
Denys Séguret Avatar answered Oct 21 '22 11:10

Denys Séguret


Use a .stop() before animate, to cancel the previous animation. I believe 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);
});
like image 41
Samuel Liew Avatar answered Oct 21 '22 09:10

Samuel Liew