Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Mouse coords 1

Status
Not open for further replies.

ashleyhales

Programmer
Jan 25, 2007
1
GB
I have been trying to find the mouse coords when I move the pointer over a div/image/etc... When I try e.clientX, e.clientY I retrieve the mouse coords relative to the browser window. This is okay but unfortunately when I scroll down the contents change position while the coords stay the same. Is there any way around this?
 
You'll want to add the scroll value to the body to get the actual value, here's an example:
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml">[/URL]
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<script type="text/javascript">

function getMouseXY(e) {
   var e = (!e) ? window.event : e;
   var posX = 0;
   var posY = 0;
   var posScroll = 0;
   if (e.pageX || e.pageY) {
      posX = e.pageX;
      posY = e.pageY;
      posScroll = document.documentElement.scrollTop;
   }
   else if (e.clientX || e.clientY) {
      if (document.body.scrollLeft || document.body.scrollTop) {
         posX = e.clientX + document.body.scrollLeft;
         posY = e.clientY + document.body.scrollTop;
         posScroll = document.body.scrollTop;
      }
      else {
         posX = e.clientX + document.documentElement.scrollLeft;
         posY = e.clientY + document.documentElement.scrollTop;
         posScroll = document.documentElement.scrollTop;
      }
   }
   document.getElementById("mousePosition").innerHTML = "x: " + posX + "\ny: " + posY;
}

document.onmousemove = getMouseXY;

</script>
<style type="text/css"></style>
</head>
<body>
<br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br />
<div id="mousePosition"></div>
<br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br /><br /><br />
</body>
</html>

-kaht

[small](All puppies have now found loving homes, thanks for all who showed interest)[/small]
 
ashleyhales, did this fix your problem?

-kaht

[small](All puppies have now found loving homes, thanks for all who showed interest)[/small]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top