I am trying to get the x and y position of mouse click in HTML file . The positions should be according to the size of html page and Mouse click can be done anywhere on the html page . How is this possible?
Asked
Active
Viewed 3,902 times
2
-
Possible duplicate of http://stackoverflow.com/questions/2159044/getting-the-x-y-coordinates-of-a-mouse-click-on-an-image-with-jquery/2159129#2159129 – Sorter Oct 17 '13 at 04:03
4 Answers
1
Look at this example:
function handleEvent(e){
var evt = e ? e:window.event;
var clickX=0, clickY=0;
if ((evt.clientX || evt.clientY) &&
document.body &&
document.body.scrollLeft!=null) {
clickX = evt.clientX + document.body.scrollLeft;
clickY = evt.clientY + document.body.scrollTop;
}
if ((evt.clientX || evt.clientY) &&
document.compatMode=='CSS1Compat' &&
document.documentElement &&
document.documentElement.scrollLeft!=null) {
clickX = evt.clientX + document.documentElement.scrollLeft;
clickY = evt.clientY + document.documentElement.scrollTop;
}
if (evt.pageX || evt.pageY) {
clickX = evt.pageX;
clickY = evt.pageY;
}
alert (evt.type.toUpperCase() + ' mouse event:'
+'\n pageX = ' + clickX
+'\n pageY = ' + clickY
+'\n clientX = ' + evt.clientX
+'\n clientY = ' + evt.clientY
+'\n screenX = ' + evt.screenX
+'\n screenY = ' + evt.screenY
)
return false;
}

Vinay Pratap Singh Bhadauria
- 9,829
- 3
- 28
- 49
0
Try this:
$('div.container').on('click',function(event){
$('div.result').html("X:"+event.pageX+" Y:"+event.pageY);
});
Working Fiddle: http://jsfiddle.net/TY75A/3/

ram
- 2,275
- 3
- 27
- 38
-
Good work ram, but OP has not tagged this question with Jquery. :( – Vinay Pratap Singh Bhadauria Oct 17 '13 at 04:10
0
With this.
addEventListener('mousedown', foo, false);
function foo(e) {
console.log(findPos(this));
}
function findPos(obj) {
var curleft = 0, curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return { x: curleft, y: curtop };
}
return undefined;
}

Arnaldo Capo
- 178
- 1
- 10
0
Try this :
$(document).ready(function() {
$('img').click(function(e) {
var offset = $(this).offset();
alert(e.clientX - offset.left);
alert(e.clientY - offset.top);
});
});

tilak
- 4,589
- 6
- 34
- 45