Home > Enterprise >  Keep calling a function while hovering AND moving over an element
Keep calling a function while hovering AND moving over an element

Time:09-25

I want to detect when the mouse is moving, while hovering over an element.

I've seen this answer, which uses an interval, but it's not the same. The interval will keep calling the function regardless of whether the mouse is moving or not. I only want to call the function IF the mouse is being moved while on top of the div.

For example, I can obviously add the mouseover event handler:

document.getElementById.addEventListener("mouseover", function( event ) {})

But this only calls the function once. Same with the hover event handler.

How can I keep calling the function while hovering AND moving, and then have the function stop calling when no longer hovering (.e.g. blur)?

CodePudding user response:

There is mousemove event. From documentation: The mousemove event is fired at an element when a pointing device (usually a mouse) is moved while the cursor's hotspot is inside it.

CodePudding user response:

would onmousemove event work? it will call the function when the mouse is moving.

MDN doc

CodePudding user response:

What you described is part of your solution. You can trigger the interval when mouseover event is triggered. The interval will trigger your function.

You can then add the mouseout event to the same element and stop the interval. This will stop the function from being triggered.

Let me know if this works for you!

  • Related