COM271, Week 10
Tracking the Mouse
Syllabus | Table of Pages | Assignments | References and Useful Links
This form shows the position of the mouse as you move it. Try it! Here's the code:
HTML
<body onmousemove = "showxy(event);">
<form>
<h4>Mouse Position</h4>
<p>x pos <input type="text" id="left" value="0" size="4"><br>
y pos <input type="text" id="top" value="0" size="4"></p>
</form>
JavaScript
function showxy(evt){
if (window.event){ evt = window.event; }
if (evt){
var x = evt.clientX;
var y = evt.clientY;
getObj('left').value = x;
getObj('top').value = y;
}}
function getObj(elemID){
return document.getElementById(elemID);}
Comment: The javaScript uses these objects:
- event: an boolean object recognized as any event by some browsers. That is, an event handler has been triggered somewhere in the contained element (here, the only event handler on the page is in the body) element, which detects any mouse event of any kind (onmousemove)
- window.event: a variation on event; that is, another boolean object recognized as an event by some browsers.
- clientX: the offset x, the same as the CSS property value for left;
- clientY: the offset y, the same as the CSS property value for top;
*sigh* Some browsers don't recognize event, but do recognize a method that is part of the window object, window.event . We try to send the script event (boolean true or false)—showxy(event)—but then test to see whether the browser recognizes window.event instead (it won't recognize both)
function showxy(evt){
if (window.event){ evt = window.event; }
When we've done both of these, we can test to see whether there have been any events detected. If there has been an event detected, we get the value of the X and Y offsets and assign their numerical value to the appropriate input boxes in the form.
Notice the effect of the absolutely positioned content div, here with a dotted red border. Outside of the div, the event cannot return clientx or clienty. If the div is not positioned (i.e., equivalent to position:static), it lies within the page and clientx and clienty can be detected outside of the borders of the div.
Okay, so we know how to get the position of the mouse in terms of x and y offset values. Next, we'll use this in an application to display text definitions using a mouseover and our mouse offset values.