This is more an urgent question than a difficult question. I'm dealing with several different web browsers and I'd like to keep the code as clean as possible. That being said I know you guys to be good at that - so here I am.
What I have is an image on a webpage. I need to capture where the user clicks in the image. I would use an image map, but I need to capture the event with javascript NOT a page refreshing a href. If you know of a way to capture the mouse click position with an image map without a page refresh I'm all ears.
My end goal for this question is being able to get where the user clicked on an image. The rest of the math is not browser specific and calls a php script to generate a new image. (Think mapquest or google map - I've intentionally not viewed their websites as this is a standalone project and I want to do it my way.)
My current solution works for IE (so long as the user doesn't scroll the page down - an unacceptable bug), Mozilla and Safari (although it might share the IE bug).
If the code is nessisary - you can view it live at
www.ninja250.org/mapThe important parts are:
Here's how I trigger the function that gets the mouse click position, I wrap an
a href around an image that I want to watch.
<a href="#" onClick="mapClick(event); return false;">
<img src="map.php?lat=0&long=-9
0&scale=18
0" id="map_img">
</a>
To get the absolute position clicked within the picture I subtract the pictures
top left position from the position clicked within the page - leaving me with a value between 0 and the images width.
// MOZILLA then IE
mapImage = document.images['map_img']
;
xClick = e.pageX ? (e.pageX - getImagePageLeft(mapImage)
) : (e.clientX - getImagePageLeft(mapImage)
);
yClick = e.pageY ? (e.pageY - getImagePageTop(mapImage))
: (e.clientY - getImagePageTop(mapImage))
;
To get the images positon on the webpage I've used a little script. I'll show the x version as it's the same for the y version. (Remember the NS4 version works fine for mozilla - even when the page is scrolled down, the IE4+ version breaks when
the page is scrolled.
var x, obj;
if (NS4) {
if (img.container != null)
return img.container.pageX + img.x;
else
return img.x;
}
if (IE4) {
x = 0;
obj = img;
while (obj.offsetParent != null) {
x += obj.offsetLeft;
obj = obj.offsetParent;
}
x += obj.offsetLeft;
return x;
}
If anyone could help me get the position clicked on the image in a cleaner and more bug free mode I'd love to give you some points.
Thanks all!
Woot.