I'm trying to get the exact mouse position relative to the window.
Here is my issue...
document.height
= 1600 (actual document size)
window.height
= 400 (viewable)
I need to figure out the mouse position relative to the window, not to the document which the pageY attribute provides.
It's for a large tooltip, which gets popped in on mouesover for a table item. If there is not enough room at the bottom of the screen (window is maxed), then the tooltip get displayed above the pointer, otherwise, below the pointer. This works fine until the document size is greater than pagesize (long table).
Thanks,
Luc
You can subtract .scrollTop()
of the window
from pageY to get the position in the window, like this:
var top = e.pageY - $(window).scrollTop();
You can give it a try here, take a look at the console.
And what about window.pageYOffset?
Demo:
<html>
<head>
<style>
html,body {padding:0;margin:0}
#content {height:2048px;background-color:#ccc;}
#status {position:fixed;top:0;left:0;}
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
$(document).mousemove(function(e){
$('#status').html(e.pageX +', '+ (e.pageY - window.pageYOffset));
});
})
</script>
<body>
<h2 id="status">0, 0</h2>
<div id="content"></div>
</body>
</html>
How about the document.body.scrollTop attribute, this contains the pixels you have scrolled. I believe a simple pageY - scrollTop should suffice then?
function showCoords(evt){
alert(
"clientX value: " + evt.clientX + "\n"
+ "clientY value: " + evt.clientY + "\n"
);
}
I think this is what you are looking for. See in details here from Mozilla Developer.