How to fire an event if the user stays up with the mouse for more than 3 seconds?

Asked

Viewed 43 times

-2

I wanted a way to only fire the event if the user remained with the mouse on the target for more than 3 seconds. If it remains for less than 2 seconds the event should not be triggered.

const e = document.querySelector("p");
e.onmouseenter = () => {
  alert(e.textContent);
};
p {
  margin: auto;
  width: fit-content;
  padding: 10px;
}
<p>Passe o mouse<p>

1 answer

2


Just use setTimeout in the mouseenter and clearTimeout in the mouseleave, example:

let timeout;

const e = document.querySelector("p");

e.onmouseenter = () => {
  // 3 segundos
  timeout = setTimeout(() => alert('Olá mundo'), 3000);
};

e.onmouseleave = () => {
  clearTimeout(timeout);
};
p {
  margin: auto;
  width: fit-content;
  padding: 10px;
}
<p>Passe o mouse<p>

Compatible with older and new browsers:

var timeout;
var e = document.querySelector("p");

e.onmouseenter = function() {
  // 3 segundos
  timeout = setTimeout(function() {
    alert('Olá mundo');
  }, 3000);
};

e.onmouseleave = function() {
  clearTimeout(timeout);
};
p {
  margin: auto;
  width: fit-content;
  padding: 10px;
}
<p>Passe o mouse<p>

  • Show brother, too good, thank you very much

  • @Erenilsonchristopher if the answer solved your problem please mark it as correct

  • 1

    Blz, I’m just waiting for the four-minute break

  • @Erenilsonchristopher I always forget that interval, long time that I do not answer on the site :) thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.