Mouse Tricks

JavaScript code for detecting mouse movement and clicks is enabled on the body of this document. Here's what it smells:


Event Detection

First, catch the events - this can be done on the document body.

<BODY onMouseMove="mouseTrack(window.event); onmousedown="mouseClick(window.event)" onmouseup="mouseClear();">

I've also disabled the right-click menu on this document, but that's another topic.

Mouse Coordinates

The mouseTrack() function tracks the movement of the mouse.

function mouseTrack(e){
  document.getElementById("mx").innerHTML = e.pageX;
  document.getElementById("my").innerHTML = e.pageY;

You can also use window.event.screenX and window.event.screenY to detect the position of the mouse within the screen (the upper left will be zero, even if the page is scrolled).

Also window.event.clientX and window.event.clientY seem to do the same thing as screenX and screenY

There is also a minor glitch: when the mouse is moved quickly outside the document area, the X or Y coordinate is not at the maximum (zero or the document width/height). So far, I've been able to live with that.

Mouse Clicks

There are a couple of functions for detecting the mouse click and clearing that value when the button is released:

function mouseClick(e){
  document.getElementById("mc").innerHTML = e.button;

function mouseClear(){
  document.getElementById("mc").innerHTML = "";

The reason for mouseClear() is that the value of the last click will be held is the variable (or object) to which it was assigned even after the button is released - so it has to be blown out manually.

One problem with the window.event.button property is that it returns a zero for a left-click, which is tricky to wrangle, as a zero is a non-value that is treated as "false" in a conditional test. If you treat it as a string, that appears to take care of it.

Another problem is that the value may vary. Zero for left and two for right seems fairly standard, but some mice have a scroll-wheel and buttons on the side that return other values. And if that's not bad enough, the user can often configure the mouse to their preference, in which case everything gets wacky.

To Do

Occurs to me that it might be useful to track the mouse position and clicks on a block-level element within the body, such as a DIV - I haven't needed to do that yet, but when I do, I'll update this page.