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.

Samich
  • 29,157
  • 6
  • 68
  • 77
suenda
  • 773
  • 1
  • 8
  • 21
  • [For focus check](http://stackoverflow.com/questions/967096/using-jquery-to-test-if-an-input-has-focus); [For timer](http://www.sean.co.uk/a/webdesign/javascriptdelay.shtm) – Vap0r Oct 24 '11 at 13:05

2 Answers2

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

genesis
  • 50,477
  • 20
  • 96
  • 125
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
    }

})();
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875