In JS, how can I get the mouse coordinates inside a DIV?

Go To StackoverFlow.com

1

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?


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?

2009-06-16 18:16
by 1qazxsw2


3

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.

2009-06-16 18:19
by Andrew Noyes
Yeah, well, I was wondering if there was a shortcut : - 1qazxsw2 2009-06-16 20:01


1

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.

2009-06-16 18:23
by jacobangel
Ads