COM271, Week 10

Tracking the Mouse

Syllabus | Table of Pages | Assignments | References and Useful Links

Mouse Position

x pos
y pos

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:

*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.


Mouse Position

x pos
y pos

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.

 

Click here to change to static position.

Click here to change back to absolute position.

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.

JS & DOM Reference

Overview

JavaScript Objects

JS Array JS Boolean JS Date JS Math JS Number JS String JS RegExp JS Global

Browser Objects

Window Navigator Screen History Location

HTML DOM Objects

Document Events Elements Anchor Area Base Body Button Form Frame/IFrame Frameset Image Input Button Input Checkbox Input File Input Hidden Input Password Input Radio Input Reset Input Submit Input Text Link Meta Object Option Select Style Table TableCell TableRow Textarea