user2227359
user2227359

Reputation: 317

Adding a delay to inline onmouseover

I am working on a page which allows you to view items on a google map. You can hover over a business address and it will move the map to that location and open an infowindow. It works perfectly, but the onmouseover event is inline because every onmouseover has a different id, which is set by a php variable.

The problem is, I need to find a way to add a delay to the onmouseover event, so that the user has to hover over the item for a couple of seconds before the onmouseover is triggered.

I've looked around at some possible solutions, but nothing seems to add the delay.

The onmouseover link looks like this...

<a onmouseover="javascript:triggerClick(<?php echo $id; ?>)" href="<?php echo $listingurl; ?>">

Any suggestions would be appreciated.

Upvotes: 1

Views: 292

Answers (2)

Zammy
Zammy

Reputation: 573

You could create something yourself. Split the onmouseover event into onmouseenter and onmouseleave. This will allow you to start a timeout in the onmouseenter event and clear it in the onmouseleave event.

function onEnter(){
  timeout = setTimeout(function(){
    //your code
  }, 1000);
}

function onLeave(){
  //in case the user leaves early stop the excution of your code
  clearTimeout(timeout);
}

This way you will have a 1 second timeout before your actions triggers and it will not trigger if the user leaves before the time runs out.

EDIT

This is the practical use case https://codepen.io/anon/pen/YEMpBx

<a onmouseover="triggerClick(<?php echo $id; ?>, this)">Foo</a>

function triggerClick(id, element){
  var timeout = setTimeout(function(){
    //your code here
  }, 1000);

  element.addEventListener('mouseleave', function triggerLeave(event){
    clearTimeout(timeout);
    element.removeEventListener('mouseleave', triggerLeave);
  });
}

Upvotes: 2

user2227359
user2227359

Reputation: 317

OK, I made it work thanks to this thread... this is what it looks like now and it works...

<a onmouseover="setTimeout(function(){ javascript:triggerClick(<?php echo $id; ?>); }, 1000);" href="<?php echo $listingurl; ?>">

Thanks

Upvotes: 0

Related Questions