jQuery get mouse position within an element

Chris Dutrow picture Chris Dutrow · Nov 22, 2010 · Viewed 246.9k times · Source

I was hoping to craft a control where a user could click inside a div, then drag the mouse, then let up on the mouse in order to indicate how long they want something to be. (This is for a calendar control, so the user will be indicating the length, in time, of a certain event)

It looks like the best way to do this would be to register a "mousedown" event on the parent div that in turn registers a "mousemove" event on the div until a "mouseup" event is triggered. The "mousedown" and "mouseup" events will define the start and end of the time range and as I follow "mousemove" events, I can dynamically change the size of the range so that the user can see what they are doing. I based this off of how events are created in google calendar.

The issue I'm having is that the jQuery event seems to only provide reliable mouse coordinate information in reference to the whole page. Is there any way to discern what the coordinates are in reference to the parent element?

Edit:

Heres a picture of what I'm trying to do: alt text

Answer

jball picture jball · Nov 22, 2010

One way is to use the jQuery offset method to translate the event.pageX and event.pageY coordinates from the event into a mouse position relative to the parent. Here's an example for future reference:

$("#something").click(function(e){
   var parentOffset = $(this).parent().offset(); 
   //or $(this).offset(); if you really just want the current element's offset
   var relX = e.pageX - parentOffset.left;
   var relY = e.pageY - parentOffset.top;
});