views:

287

answers:

1

Hi guys,

let me explain my problem. I have a mouseout event assigned to a div tag with an id of calendar. Now when this handler is called (when the mouse is not over the calendar div), i want to wait 2 seconds, then see if the mouse is still not over the calendar div. If the mouse i still out then do a function, if not then do nothing.

I use the prototype javascript library. My code is as follows:

$('calendar').observe('mouseout', function (event){ 
    setTimeout(/* call this event again */, 2000);
}

Thanks

+2  A: 
$('calendar').observe('mouseout', function(e) {
   myTimeout = setTimeout(function() { /* stuff to do after 2 secs */, 2000);
});

$('calendar').observe('mouseover', function(e) {
   if(myTimeout) window.clearTimeout(myTimeout);
});
David Hedlund
where you have /* stuff to do after 2 secs */ this is where i want to see if the mouse is still over the calendar div or not. This is what im not sure on
phpNutt
Yes, well, if you check out the stuff in 'mouseover' below, that actually cancels the timer when the element is mouseover'ed again, so that means, if that code executes, you know per definition that it has not been mouseovered in 2 seconds, so what you want to do, is safe to do there
David Hedlund
This should work as long as you make sure to declare the myTimeout variable outside the scope of these two functions.
Shawn Steward
That is not required, actually. If you introduce a variable without the 'var' keyword, it'll become a global variable, no matter in which scope you introduce it (go ahead and try it). Before that has happened, mouseover won't cause an error, because we're checking so that it exists, and after that's happened, on first mouseout, it won't be a problem either, as it'll become global
David Hedlund