tags:

views:

465

answers:

3

In JS, how can I get the mouse coordinates inside a DIV? if I use event.pageX, it will only work if the DIV is at the top left corner of the page... otherwise, I have to know the position of the DIV in the page and subtract event.pageX from that. This is hard to do when I generate the DIVs dynamically since I have to keep track of the position of each DIV. Any ideas?

+2  A: 

It sounds to me like you answered your own question. I'm not aware of any shortcuts for finding the cursor position from within a div simpler than subtracting the x and y coordinates of the mouse from the x and y coordinates of the upper left corner of the div. Just make sure you cache the location of the div as it changes to avoid a DOM lookup each time the mouse cursor moves.

Andrew Noyes
Yeah, well, I was wondering if there was a shortcut :)
1qazxsw2
+2  A: 

It's not too hard. Each element has an offsetTop and offsetLeft property. You can use that with current mouse position to figure out the relative position.

jacobangel
A: 

It seems like event.layerX and event.layerY works find in FF if I define the DIV with an absolute position. Here is a short example:

http://www.zangware.com/divpos.html

But in IE, event.layerX/Y is undefined inside the DIV. Any ideas?

1qazxsw2