Index

How do I get the mouse position on an element?

When an event handler such as mousedown or mousemove is called, several mouse-position related properties can be retrieved. You can get the mouse pointer position where the event occured on the window using the clientX and clientY properties of the event object. These properties contain the horizontal and vertical position of the mouse pointer relative to the upper-left corner of the window (or frame).

The event's target property contains the element where the mouse event occured. To get the pointer position relative to this element instead of the window, you can subtract the element's position from the event position.

Every XUL element has a boxObject property which can be used to retrieve the position and size of the element. The box object contains two properties x and y which return the position of an element.

The example below has a number of elements. Moving the mouse around will display the coordinates of the mouse in a label, relative to the window and relative to the element the mouse is over.

View
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<window id="mousexy" title="Mouse Position"
        onmousemove="adjustCoords(event);"
        xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script>
function adjustCoords(event)
{
  var pos=document.getElementById("pos");
  // Use the clientX and clientY properties to get the position of the
  // mouse relative to the window. The event object is passed as an
  // argument to this function.
  var lbl="On Window: " + "(" + event.clientX + "," + event.clientY + ")";
  // Calculate the position of the mouse over an element. To do this, subtract
  // the position of the element the mouse is over from the mouse position. The
  // element's position can be determined from its boxObject.
  var offsetX = (event.clientX - event.target.boxObject.x);
  var offsetY = (event.clientY - event.target.boxObject.y);
  // Assign the offsets to the text of a label.
  lbl+=" Relative to: " + event.target.tagName + "(" + offsetX + "," + offsetY + ")";
  pos.setAttribute("value",lbl);
}
</script>
<label id="pos" value=" "/>
<hbox>
  <label value="Enter some text:"/><textbox/>
  <button label="OK"/>
</hbox>
<listbox>
  <listitem label="Document"/>
  <listitem label="Image"/>
  <listitem label="Video"/>
  <listitem label="Audio"/>
</listbox>
</window>
Copyright © 1999 - 2005 XULPlanet.com