Entry
How can I display the x/y mouse coordinates on a web page (not in the status bar) ?
Apr 28th, 2001 23:03
Colin Fraser, alban saporos,
You can trap the x and y coords of the pointer and use them for all
sorts of things. The only problem I had was to make it cross browser. I
used two sources, The Dark Side JScript Guide and Netscape's JavaScript
Guide (page 163 of the PDF). While normally useless, at least the
JScript guide pointed me in the right direction.
<html>
<head>
<script language="JavaScript"><!-- //hide from older browsers
/*Determine the browser, naming which event and registering the event
handler */
if (navigator.appName == 'Netscape') {
document.captureEvents(Event.MOUSEMOVE);
document.onmousemove = nnPointerPosn;
}
/*getting the coordinates of the pointer in Netscape, defining the the
event handler */
function nnPointerPosn(a) {
if (a.screenX != document.pointxy.xposn.value && a.screenY !=
document.pointxy.yposn.value) {
document.pointxy.xposn.value = a.screenX;
document.pointxy.yposn.value = a.screenY;
}
}
/* for IE */
function iePointerPosn() {
if (window.event.x != document.pointxy.xposn.value &&
window.event.y != document.pointxy.yposn.value) {
document.pointxy.xposn.value = window.event.x;
document.pointxy.yposn.value = window.event.y;
}
}
//-->
</script>
</head>
<!call the function for IE in the body tag>
<body onMousemove="iePointerPosn()">
<form name="pointxy">
X posn: <input type="text" name="xposn" size="5"> Y posn: <input
type="text" name="yposn" size="5">
</form>
</body>
</html>
This only works in NN and IE I have no idea about any other browser, I
have not used a Mac or Unix versions of these programs, but this code
should work on them. Other browsers are not even considered here, so I
am not sure if this will work on them. This code is not guarranteed, but
it works on my pc.
Please note that the nn and ie versions handle the pointer differently,
so different versions of the same script are used. The iePointerMove
function is called in the body tag.
While this code works, and appears to be a good response to your
question, if you move your pointer very slowly over the page, the
display does not necessarily update. The reason for this is not so
obvios but is likely to be a limitation in JavaScript.