[Mapserver-users] How to get X and Y pixel coordinates with JavaScript

Jan Hartmann j.l.h.hartmann at uva.nl
Wed Jul 21 11:27:24 EDT 2004


Merlos wrote:
> 
> 	Maybe someone can help me. I was wondering if when an user clicks on the 
> image that is on an <input type="image"> element it is possible to capture 
> the X and Y coordinates before the submission is done. I mean:
> 
> <script type="text/javascript">
> 
> function formSubmit() {
> //Here get the X and Y coords in pixels... Is it possible? How?
> }
> <form name="apatruyando" action="JavaScript:formSubmit()">
> <input type="image" src="image_url.png" />
> </form>
> 

Hi Merlos,

The following works for IE5.5 and up and Netscape6/Mozilla. Not sure 
about others.

function getCrd(e) {
   if (document.all) {
      X = e.clientX + document.body.scrolLeft
      Y = e.clientY + document.body.scrolTop
   } else {
      X = e.clientX + window.scrollX
      Y = e.clientY + window.scrollY
   }
    ... ///anything else you want to do
}

If you have an image defined as:

<img src=ïmage_url.png id=myImgId>

you can assign this function to it by:

var myImg = document.getElementById("myImgId")
myImg.onmousedown = getCrd   //NB *without* parentheses

Now every time you click somewhere in the image, the function will 
compute the coordinates of the click and execute everything else. You 
don't need to encapsulate the image in a form this way.

This way, the coordinate is computed from the top left corner of the 
page, even if the page is scrolled. If you want the coordinate relative 
to the image, regardless where this is on the screen, you need to 
compute the top left corner of the image:

var node = myImg
var left = node.offsetLeft
var top = node.offsetTop
while (node.parentNode) {
    node = node.parentNode
    if (node.offsetLeft) {
       left = left + node.offsetLeft
       top = top + offsetTop
}

Hope this helps,

Jan





More information about the mapserver-users mailing list