4

I am trying to get mouse pointer position on mousedown and mouseup event. There is a div named test and i want to get position when mousedown and mouseup happen within div area. And I am taking div as my surface so the mousedown and mouseup position should be related to div. I have a pdf inside that div so, the coordinates i get will help me to highlight the pdf.

I tried this, but its not working fine.

function getPosition(element) {
    var xPosition = 0;
    var yPosition = 0;
    while (element) {
        xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
        yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
        element = element.offsetParent;
    }
    return { x: xPosition, y: yPosition };
}
$("#test").mousedown(function(e){
  var parentPosition = getPosition(e.currentTarget);
  startX = e.clientX - parentPosition.x;
  startY = (e.clientY - parentPosition.y)*2.5;
});
 $("#test").mouseup(function(e){
  var parentPosition = getPosition(e.currentTarget);
  endX = e.clientX - parentPosition.x;
  endY=   (e.clientY - parentPosition.y)*2.5;
});
Dhwani
  • 7,484
  • 17
  • 78
  • 139
  • Code for getPosition? have you used position or offset? – Sid Jun 27 '14 at 06:06
  • doesnot this help you? http://stackoverflow.com/a/4517215/903790 – doniyor Jun 27 '14 at 06:08
  • by relative to div do you mean if you click in the top left corner of the div you would get x = 0,y = 0, and if you click in the bottom right corner you would get x = div width,y = div height – Patrick Evans Jun 27 '14 at 06:19

1 Answers1

2

The coordinates of the mouse relative to the div are stored in the offsetX, offsetY properties of the event object

$("#someDiv").click(function(e){
   var x = e.offsetX;
   var y = e.offsetY;
});

So if you have a div with a width of 100 and a height of 50, and click exactly in the center of the div then

x = 50, y = 25

JSFiddle Demo

Patrick Evans
  • 41,991
  • 6
  • 74
  • 87