user13484252
user13484252

Reputation: 71

Javascript on hover for > 3 seconds

I am trying to write vanilla javascript which will listen for if a img is hovered over, and if the image is hovered over for 3 seconds it opens a new tab. Currently I am doing something like this

 img.addEventListener('mouseover', changeDefOver);
img.setAttribute( 'class', 'myCssClass' );
function changeDefOver(e) {
  window.open("https://www.geeksforgeeks.org", "_blank");
}

but this will do it instantly and does not check for the 3 seconds. I also cannot use jQuery. Any ideas?

Upvotes: 1

Views: 2024

Answers (2)

webdevdani
webdevdani

Reputation: 1102

Popup blocker would probably block this, but you could use setTimeout.

let hoverTimeout;

function changeDefOver(e) {
  hoverTimeout = setTimeout(() => {
     window.open("https://www.geeksforgeeks.org", "_blank");
  }, 3000);
}

function clearHoverTimeout() {
   clearTimeout(hoverTimeout);
}

But you'll also need to clean up the timeout:

img.addEventListener('mouseout', clearHoverTimeout);

Upvotes: 0

epascarello
epascarello

Reputation: 207537

So use timeout and remove the timeout if the user leaves the element.

function over() {
  this.timeout = window.setTimeout(function () {
    console.log('here')
  }, 3000)
}

function left() {
  if (this.timeout) window.clearTimeout(this.timeout)
}

img.addEventListener('mouseenter', over);
img.addEventListener('mouseleave', left);

Upvotes: 3

Related Questions