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

nice ass picture nice ass · Feb 5, 2013 · Viewed 52.6k times · Source

event.pageY gets you 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).

Answer

lostsource picture lostsource · Feb 5, 2013

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

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