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:
I use this piece of code, its quite nice :)
One way is to use the jQuery
offset
method to translate theevent.pageX
andevent.pageY
coordinates from the event into a mouse position relative to the parent. Here's an example for future reference:To get the position of click relative to current clicked element
Use this code
Here is one that also gives you percent position of the point in case you need it. https://jsfiddle.net/Themezly/2etbhw01/
This solution supports all major browsers including IE. It also takes care of scrolling. First, it retrieves the position of the element relative to the page efficiently, and without using a recursive function. Then it gets the x and y of the mouse click relative to the page and does the subtraction to get the answer which is the position relative to the element (the element can be an image or div for example):
@AbdulRahim answer is almost correct. But I suggest the function below as substitute (for futher reference):