javascriptheightdom-eventsviewport

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


event.pageY gets the mouse position relative to the entire document height (document.documentElement.offsetHeight I assume).

But how do I get the mouse position relative to the current viewport, which is document.documentElement.clientHeight?

For example, if the browser window size has a 720 pixel height, I scroll down 3 pages and keep the mouse in the middle of the window, the position should be "360", not 1800 (720 x 3 - 720 / 2).


Solution

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

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