1

I have onmouseenter event that I want to trigger only if the mouse spends more than n seconds inside the object.

$('#object').live('mouseenter', function() { 

// code that will execute only if mouse spends more than n seconds

});

I'd appreciate any help.

1

2 Answers 2

4
var timeout;
$('#object').live('mouseenter', function() { 
    timeout = setTimeout(function(){
        // code that will execute only if mouse spends more than n seconds
    }, 2000);

});

$('#object').live('mouseleave', function() { 
   clearTimeout(timeout); 
});

so for example to change text to "Working" and change color to red, following code is fine

<div id="object">Hover here and wait</div> 
<script> 
var timeout; 
var object = $("#object"); 
object.live('mouseenter', function() {  
    timeout = setTimeout(function(){ 

        object.css({'color': 'red', 'font-size': '400%'}); 
        object.html('Working'); 
    }, 2000); 
}); 

object.live('mouseleave', function() {  
   clearTimeout(timeout);  
}); 
</script>

demo

Sign up to request clarification or add additional context in comments.

Comments

0

You can set a function to be called after a delay, and cancel it if you see mouseleave:

(function() {
    var timer = 0; // 0 is a safe "no timer" value

    $('#object').live('mouseenter', function() {
        // I'm assuming you don't want to stomp on an existing timer
        if (!timer) {
            timer = setTimeout(doSomething, 1000); // Or whatever value you want
        }
    }).live('mouseleave', function() {
        // Cancel the timer if it hasn't already fired
        if (timer) {
            clearTimeout(timer);
            timer = 0;
        }
    })

    function doSomething() {
        // Clear this as flag there's no timer outstanding
        timer = 0;

        // Do your stuff
    }

})();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.