How to get the mouse position relative to the window viewport in javascript? How to get the mouse position relative to the window viewport in javascript? javascript javascript

How to get the mouse position relative to the window viewport in javascript?


Try using event.clientY that should always return the correct value regardless of scrolling

https://developer.mozilla.org/en-US/docs/DOM/event.clientY


I was in similar situation, I required cursor's coordinates w.r.t the Viewport (since my page was scrollable).

I tried other answers here, they didn't seem to work once the screen was scrolled (they worked well with non-scrollable pages).

Upon reading a few documentation page of https://developer.mozilla.org/en-US/docs/Web/API/MouseEventI found that while working with scrollable page, if you need X and Y coordinates w.r.t the current Viewport (i.e. even if scrolled), it would be better to useevent.pageX instead.

var pageX = MouseEvent.pageX;

https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/pageX