I need to execute a function when the mouse pauses on an element for 3 seconds.
I tried to do this with the mouseover event, but the problem is that my function is triggered immediately when the mouse enters the element
element.addEventListener("mouseover", () => {
setTimeout(() => {
myFunction()
},3000)
})
Is there a way to trigger the mouseover event after the user pauses on the element for 3 seconds?
Is there a better way?, please help me
>Solution :
Rather than mouseover, I’d probably use mouseenter since mouseover fires repeatedly as the mouse moves across the element. Then you can use mouseleave to cancel the timer if the mouse leaves the element before the three seconds are up.
Something like this:
const target = document.querySelector(".target");
let timer = 0;
target.addEventListener("mouseenter", () => {
timer = setTimeout(() => {
timer = 0;
console.log("Timer fired");
}, 3000);
console.log("Timer started");
});
target.addEventListener("mouseleave", () => {
if (timer) {
clearTimeout(timer);
timer = 0;
console.log("Timer cancelled");
}
});
<div>Not a target</div>
<div>Not a target</div>
<div>Not a target</div>
<div>Not a target</div>
<div class="target">Target </div>
<div>Not a target</div>
<div>Not a target</div>
<div>Not a target</div>
That example only handles a single element (because timer is a single variable), but if you need to handle multiple, you could maintain a WeakMap using the element as the key and the timer handle as the value. (A WeakMap so that if the elements are removed from the DOM at some point, the map entries for them don’t stick around unnecessarily.)