5

How can I check and see if the cursor is over an element? I know there is an event onMouseOver and onMouseEnter, but if the cursor is over the element on page load, the event doesn't fire.

So how can I check to see if the cursor is over an element, probably in the useEffect function.

Jessica
  • 9,379
  • 14
  • 65
  • 136
  • You can read about the useLayoutEffect hook. – Daimellah Sofiane Nov 12 '20 at 17:44
  • I don't think it will fire before the `DOMContenLoaded` event is fired. Your event handlers are attached to elements inside the DOM and you are registering handlers during or after the DOM has loaded. So if your cursor is on the page where the desired element should be it will not fire unless you move the cursor after loading is complete. – Abrar Hossain Nov 12 '20 at 17:48
  • @AbrarHossain Exactly, so how can I check if the cursor is over the element on startup? – Jessica Nov 12 '20 at 17:50

1 Answers1

3

TLDR: No, it's not possible to get any information about the cursor until a mouse event has occurred.

The mouse position is reported to the browser by the mouse event's pageX, pageY, offsetX, offsetY, screenX, screenY. (Source: MDN Docs: Mouse Event.) And the only events available to the mouse that would reveal cursor location would require movement or interaction by the user. If the JS environment does not know where the cursor even is, then it's not going to know if it's hovering over an element.

You might want to take a quick look at this SO answer: StackOverflow: How to get the mouse position without events (without moving the mouse)?.

This is probably for security reasons. If one website is allowed to know where the cursor was on another website, what else can they know? Can they know what the cursor was hovering over? Can they know its id and other attributes? Are they just allowed to access anything in the event sequence? That probably wouldn't be good. The ideal security gives every website gets its own event-chain: and without mouse movement, the website doesn't even know there's a mouse.

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133