Question

I have a link:

<a href="#" id="link">Here's my link</a>

This is not a normal clickable link, it's coded in jQuery like this:

 $("#link").hover(function(e) { 
    e.preventDefault();   
    $("#tv").stop().animate({marginLeft: "50px"});
    $("#tv img)").animate({opacity: 1});
})  

So after hovering unclickable link there's change of #tv's margin and opacity.

Is there any way of making this work only after the user hovers the link area with pointer for more than two seconds?

Because now everything happens in real time.

I know there's delay(), but it doesn't work because it just delays the animation and in this case I don't want any action if the pointer is over for less than two seconds.

Possible without a loop?

Was it helpful?

Solution

var animateTimeout;

$("#link").hover(function() {
  if (animateTimeout != null) { 
    clearTimeout(animateTimeout); 
  }
  animateTimeout = setTimeout(animate, 2000);
}, function() {
  clearTimeout(animateTimeout);
});

function animate() {
  //do animation
}

OTHER TIPS

What you're after is called hoverIntent.

You just need a setTimeout() to delay the code, along with a clearTimeout() to clear it if the user leaves the link within 2 seconds.

Example: http://jsfiddle.net/mNWEq/2/

$("#link").hover(function(e) {
    e.preventDefault();
    $.data(this).timeout = setTimeout(function() {
        $("#tv").stop().animate({marginLeft: "50px"});
        $("#tv img)").animate({opacity: 1});
    }, 2000);
}, function(e) {
    clearTimeout($.data(this,'timeout'));
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top