Month: June 2007

Getting Coordinates of a mouse click

Posted by – June 30, 2007

Today I was working on an image editing program, and wanted to determine the x and y coordinates on an image. I knew that imagemaps will give you the coordinates that you clicked on, but I wanted to mimic this behavior in javascript.

It turns out there are 2 ways to do this: If you are using IE (then shame on you!) you can get the coordinates using an offsetX and offsetY.For example, an an onclick handler to your image, passing in the event (ex: <img onclick=’getCoords(e)’ …) then inside the getCoords function, you can use e.offsetX and e.offsetY.

But what If I am awesome, and thus don’t use IE, you might ask. Well, it is only slightly more work. Other browsers give you a pageX and pageY, so you simply have to compare those values with the images values, and do some math to get your coordinates. The image offsets can be found with offsetTop and offsetLeft so to get the x value, you would do:


var xOffset = e.pageX - document.getElementById("thePictureId").offsetLeft

Problem Solved!