Faqts : Computers : Programming : Languages : JavaScript : Event handling

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

20 of 22 people (91%) answered Yes
Recently 10 of 10 people (100%) answered Yes

Entry

How can I find the event coordinates relative to the element the event is fired on?
How can I find the event coordinates relative to the element the event is fired on?

Jan 24th, 2002 04:33
Martin Honnen,


IE4+ offers
  window.event.offsetX
  window.event.offsetY
as properties of the event object indicating the offset of the event 
to the offsetLeft/offsetTop coordinates of
  window.event.srcElement
NN6's event system doesn't know a srcElement, instead it has an
  event.target
property which can be a text node or an element node. Thus for NN6 to 
find something like a srcElement you need to check
  if (event.target.nodeType != 1)
    var el = event.target.parentNode;
Computing the offsets is possible by computing the absolute event 
coordinates
  window.pageXOffset + event.clientX
  window.pageYOffset + event.clientY
and substracting the absolute coordinates of the element.
Here is code that has been tested to work with IE6, Opera 6 and NN6, 
it should work with IE4+.
<html>
<head>
<title>
offsetX/offsetY
</title>
<script type="text/javascript">
function getPageCoords (element) {
  var coords = {x: 0, y: 0};
  while (element) {
    coords.x += element.offsetLeft;
    coords.y += element.offsetTop;
    element = element.offsetParent;
  }
  return coords;
}
function getOffsets (evt) {
  if (typeof evt.offsetX != 'undefined')
    return { x: evt.offsetX, y: evt.offsetY }
  else if (evt.target) {
    if (window.opera)
      var element = evt.target;
    else
      var element = evt.target.nodeType == 1 ? evt.target : 
evt.target.parentNode;
    var eventCoords = {
      x: evt.clientX + window.pageXOffset,
      y: evt.clientY + window.pageYOffset
    };
    var elCoords = getPageCoords(element);
    return {x: eventCoords.x - elCoords.x, y: eventCoords.y - 
elCoords.y};
  }
}
</script>
</head>
<body>
<p style="background-color: lightblue;"
   onmousemove="var offsets = getOffsets(event);
                window.status = offsets.x + ':' + offsets.y;"
>
Kibology for all
</p>
<div style="position: absolute;
            left: 200px; top: 200px;
            width: 100px; height: 100px;
            background-color: lightyellow;"
     onmousemove="var offsets = getOffsets(event);
                  window.status = offsets.x + ':' + offsets.y;"
>
Kibology
</div>
</body>
</html>