How do I trigger a function after the user has had his mouse over an element for x seconds?
Here's my code:
$('#e开发者_运维知识库lement').hover(function()
{
window.setTimeout(function()
{
alert('hovered for 2 seconds');
}, 2000);
},
function()
{
alert('mouse left');
});
But it doesn't quite work the way I want it to.
What I'm actually trying to do is, if the user has his mouse over the #element
for 2 seconds it should trigger the alert()
. But if he moves his mouse away from the #element
before the 2 seconds are over nothing should happen.
And the problem with the current code is that if I move my mouse over the #element
and move it away before the 2 secs are over, it still triggers the alert()
after 2 secs.
I really hope this makes sense.
You are almost there. You need to store the result of setTimeout
(I used jQuery's data), then call clearTimeout
with the same value.
$('#element').hover(function()
{
$(this).data('timeout', window.setTimeout(function()
{
alert('hovered for 2 seconds');
}, 2000));
},
function()
{
clearTimeout($(this).data('timeout'));
alert('mouse left');
});
http://jsfiddle.net/nCcxt/
精彩评论