Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I execute a function after a two-second hover?

This is my current code

google.maps.event.addListener(marker, `mouseover`, function() { 
  alert('loaded when i hovered');
});

but I want the function to be executed if the mouse is over the element for two seconds.

I tried this but it didn't work.

 google.maps.event.addListener(marker, `mouseover  2000`, function() { 
   alert('loaded after then when i stay mouse 2 sec'); 
 });

What do I need to do to make the function execute after a two-second hover?

like image 537
Dest Avatar asked Oct 17 '12 14:10

Dest


2 Answers

You need to use a timer. Set it in mouseover, then in the timer callback do your work; also you need to handle a mouseout event where you stop the timer.

var timeoutId = null;
google.maps.event.addListener(marker, 'mouseover',function() { 
   timeoutId = window.setTimeout(function(){
     alert("I did it!");
   }, 2000);
 } );

// Cancel your action if mouse moved out within 2 sec
google.maps.event.addListener(marker, 'mouseout',function() { 
  window.clearTimeout(timeoutId)
});
like image 65
Andrey Avatar answered Sep 30 '22 01:09

Andrey


It would be something like this, using setTimeout

var timer;

google.maps.event.addListener(marker, 'mouseover', function() {        
   timer = window.setTimeout(function(){
     alert("Stackoverflow Rocks!!!");
   }, 2000);
 } );

google.maps.event.addListener(marker, 'mouseout', function() {        
   window.clearTimeout(timer);
 } );
like image 34
Cristiano Fontes Avatar answered Sep 30 '22 03:09

Cristiano Fontes