Entry
How can I in an event handler like onclick get the coordinates relative to the element (for instance an img) clicked?
How can I in an event handler like onclick get the coordinates relative to the element (for instance an img) clicked?
Jul 7th, 2001 13:50
Gabriel Suchowolski, Martin Honnen,
IE provides properties for that
window.event.offsetX
window.event.offsetY
NN6 doesn't provide that so you need to use the
event.clientX
event.clientY
compute the coordinates of the element (for instance img) on the page
and substract them to find the offset relative to the element.
Here is code that demonstrates that:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>
img click coordinates
</title>
<script type="text/javascript">
function imgClickHandler (evt, img) {
if (window.event)
alert(window.event.offsetX + ':' + window.event.offsetY);
else if (evt.target) {
var coords = {x: 0, y: 0 };
var el = evt.target;
do {
coords.x += el.offsetLeft;
coords.y += el.offsetTop;
}
while ((el = el.offsetParent));
var offsetX = evt.clientX - coords.x;
var offsetY = evt.clientY - coords.y;
alert(offsetX + ':' + offsetY);
}
}
</script>
</head>
<body>
Kibology for all.
<br>
All for Kibology.
<img src="kiboInside.gif"
onclick="imgClickHandler (event, this)">
</body>
</html>
- - - - - -
NOTE:
For Layers (DIV's) in NS use
e.layerX
e.layerY
IDEA:
Another could be to embed the img on a div an compute position in the
div.