Search code examples
javascriptjqueryhoverdelay

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);
});

Solution

  • 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.