[jquery] jQuery get mouse position within an element

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

This question is related to jquery mouseevent

The answer is


Here is one that also gives you percent position of the point in case you need it. https://jsfiddle.net/Themezly/2etbhw01/

_x000D_
_x000D_
function ThzhotspotPosition(evt, el, hotspotsize, percent) {_x000D_
  var left = el.offset().left;_x000D_
  var top = el.offset().top;_x000D_
  var hotspot = hotspotsize ? hotspotsize : 0;_x000D_
  if (percent) {_x000D_
    x = (evt.pageX - left - (hotspot / 2)) / el.outerWidth() * 100 + '%';_x000D_
    y = (evt.pageY - top - (hotspot / 2)) / el.outerHeight() * 100 + '%';_x000D_
  } else {_x000D_
    x = (evt.pageX - left - (hotspot / 2));_x000D_
    y = (evt.pageY - top - (hotspot / 2));_x000D_
  }_x000D_
_x000D_
  return {_x000D_
    x: x,_x000D_
    y: y_x000D_
  };_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
$(function() {_x000D_
_x000D_
  $('.box').click(function(e) {_x000D_
_x000D_
    var hp = ThzhotspotPosition(e, $(this), 20, true); // true = percent | false or no attr = px_x000D_
_x000D_
    var hotspot = $('<div class="hotspot">').css({_x000D_
      left: hp.x,_x000D_
      top: hp.y,_x000D_
    });_x000D_
    $(this).append(hotspot);_x000D_
    $("span").text("X: " + hp.x + ", Y: " + hp.y);_x000D_
  });_x000D_
_x000D_
_x000D_
});
_x000D_
.box {_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
  background: #efefef;_x000D_
  margin: 20px;_x000D_
  padding: 20px;_x000D_
  position: relative;_x000D_
  top: 20px;_x000D_
  left: 20px;_x000D_
}_x000D_
_x000D_
.hotspot {_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  height: 20px;_x000D_
  width: 20px;_x000D_
  background: green;_x000D_
  border-radius: 20px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="box">_x000D_
  <p>Hotspot position is at: <span></span></p>_x000D_
</div>
_x000D_
_x000D_
_x000D_


I would suggest this:

e.pageX - this.getBoundingClientRect().left

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):

function getXY(evt) {
    var element = document.getElementById('elementId');  //replace elementId with your element's Id.
    var rect = element.getBoundingClientRect();
    var scrollTop = document.documentElement.scrollTop?
                    document.documentElement.scrollTop:document.body.scrollTop;
    var scrollLeft = document.documentElement.scrollLeft?                   
                    document.documentElement.scrollLeft:document.body.scrollLeft;
    var elementLeft = rect.left+scrollLeft;  
    var elementTop = rect.top+scrollTop;

        if (document.all){ //detects using IE   
            x = event.clientX+scrollLeft-elementLeft; //event not evt because of IE
            y = event.clientY+scrollTop-elementTop;
        }
        else{
            x = evt.pageX-elementLeft;
            y = evt.pageY-elementTop;
    }

To get the position of click relative to current clicked element
Use this code

$("#specialElement").click(function(e){
    var x = e.pageX - this.offsetLeft;
    var y = e.pageY - this.offsetTop;
}); 

I use this piece of code, its quite nice :)

    <script language="javascript" src="http://code.jquery.com/jquery-1.4.1.js" type="text/javascript"></script>
<script language="javascript">
$(document).ready(function(){
    $(".div_container").mousemove(function(e){
        var parentOffset = $(this).parent().offset();
        var relativeXPosition = (e.pageX - parentOffset.left); //offset -> method allows you to retrieve the current position of an element 'relative' to the document
        var relativeYPosition = (e.pageY - parentOffset.top);
        $("#header2").html("<p><strong>X-Position: </strong>"+relativeXPosition+" | <strong>Y-Position: </strong>"+relativeYPosition+"</p>")
    }).mouseout(function(){
        $("#header2").html("<p><strong>X-Position: </strong>"+relativeXPosition+" | <strong>Y-Position: </strong>"+relativeYPosition+"</p>")
    });
});
</script>

If you make your parent element be "position: relative", then it will be the "offset parent" for the stuff you're tracking mouse events over. Thus the jQuery "position()" will be relative to that.


@AbdulRahim answer is almost correct. But I suggest the function below as substitute (for futher reference):

function getXY(evt, element) {
                var rect = element.getBoundingClientRect();
                var scrollTop = document.documentElement.scrollTop?
                                document.documentElement.scrollTop:document.body.scrollTop;
                var scrollLeft = document.documentElement.scrollLeft?                   
                                document.documentElement.scrollLeft:document.body.scrollLeft;
                var elementLeft = rect.left+scrollLeft;  
                var elementTop = rect.top+scrollTop;

                x = evt.pageX-elementLeft;
                y = evt.pageY-elementTop;

                return {x:x, y:y};
            }




            $('#main-canvas').mousemove(function(e){
                var m=getXY(e, this);
                console.log(m.x, m.y);
            });