Reputation: 7626
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;
});
Upvotes: 4
Views: 3021
Reputation: 42736
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
Upvotes: 2