Getting the Mouse position in jQuery is very simple. However, getting the position from within an element take some extra steps.
Normally, a javascript event such as onmousemove would use event.layerX and event.layerY to get the coordinates of our mouse when it moves.
For jQuery, pageX and pageY will return values from the top left of the page and not the layer. Unless the element you’re working with is left-aligned, you need to calculate the offset of that element as well. Not only that (unless there is a better way to do this) the offset values returned doesn’t include the offset values of the parent tag.
In this example, I have two divs.
And you can imagine that #frame is centered and has padding. Getting #content’s offset won’t include anything outside of the frame so $(#content).offset().left; would only get you the distance of itself and its parent.
Get your layerX for jQuery
For this example, we are using a known set of divs so we can just write out each div in this script.
The variables are declared inside the event function to handle window resizing. Now were this a more complicated page and the element in question has deeply nested or even dynamically generated, writing our all the parent tags wouldn’t necessarily work (or be very efficient).* But the approach would remain the same. That’s it!
*standard apology for poor code writing skills