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
2
Answers
Rather than
mouseover
, I’d probably usemouseenter
sincemouseover
fires repeatedly as the mouse moves across the element. Then you can usemouseleave
to cancel the timer if the mouse leaves the element before the three seconds are up.Something like this:
That example only handles a single element (because
timer
is a single variable), but if you need to handle multiple, you could maintain aWeakMap
using the element as the key and the timer handle as the value. (AWeakMap
so that if the elements are removed from the DOM at some point, the map entries for them don’t stick around unnecessarily.)To achieve that behaviour in your app, you need to combine
mouseover
andmouseout
events.The key issue is to reset the timer every time the cursor hovers over an element and leaves it.