'How to get the mouse position relative to the window viewport in javascript?
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).
Solution 1:[1]
Try using event.clientY
that should always return the correct value regardless of scrolling
Solution 2:[2]
Use event.clientY
to get the mouse position relative to the browser viewport (Compatibility table).
Solution 3:[3]
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/MouseEvent
I 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 use
event.pageX
instead.
var pageX = MouseEvent.pageX;
https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/pageX
Solution 4:[4]
Here is a code example:
document.addEventListener('mousemove', event => {
console.log(event.clientY) // THIS should do what you want
})
Click the snippet below to see it in action:
document.addEventListener('mousemove', e => {
document.getElementById('log').innerHTML = `
Relative to screen:<br>
e.screenX: <b>${e.screenX}</b><br>
e.screenY: <b>${e.screenY}</b><br><br>
Relative to viewport:<br>
e.clientX: <b>${e.clientX}</b><br>
e.clientY: <b>${e.clientY}</b>`
})
<div id='log'></div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | lostsource |
Solution 2 | Bergi |
Solution 3 | Nikhil Anand |
Solution 4 | TOPKAT |