I would like to use jQuery to get the X/Y coordinates of a click event on an image. The coordinates should be relative to the image, not relative to the whole page
This question is related to
jquery
Here is a better script:
$('#mainimage').click(function(e)
{
var offset_t = $(this).offset().top - $(window).scrollTop();
var offset_l = $(this).offset().left - $(window).scrollLeft();
var left = Math.round( (e.clientX - offset_l) );
var top = Math.round( (e.clientY - offset_t) );
alert("Left: " + left + " Top: " + top);
});
note! there is a difference between e.clientX
& e.clientY
and e.pageX
and e.pageY
try them both out and make sure you are using the proper one. clientX
and clientY
change based on scrolling position
The below code works always even if any image makes the window scroll.
$(function() {
$("#demo-box").click(function(e) {
var offset = $(this).offset();
var relativeX = (e.pageX - offset.left);
var relativeY = (e.pageY - offset.top);
alert("X: " + relativeX + " Y: " + relativeY);
});
});
Ref: http://css-tricks.com/snippets/jquery/get-x-y-mouse-coordinates/
Take a look at http://jsfiddle.net/TroyAlford/ZZEk8/ for a working example of the below:
<img id='myImg' src='/my/img/link.gif' />
<script type="text/javascript">
$(document).bind('click', function () {
// Add a click-handler to the image.
$('#myImg').bind('click', function (ev) {
var $img = $(ev.target);
var offset = $img.offset();
var x = ev.clientX - offset.left;
var y = ev.clientY - offset.top;
alert('clicked at x: ' + x + ', y: ' + y);
});
});
</script>
Note that the above will get you the x and the y relative to the image's box - but will not correctly take into account margin, border and padding. These elements aren't actually part of the image, in your case - but they might be part of the element that you would want to take into account.
In this case, you should also use $div.outerWidth(true) - $div.width()
and $div.outerHeight(true) - $div.height()
to calculate the amount of margin / border / etc.
Your new code might look more like:
<img id='myImg' src='/my/img/link.gif' />
<script type="text/javascript">
$(document).bind('click', function () {
// Add a click-handler to the image.
$('#myImg').bind('click', function (ev) {
var $img = $(ev.target);
var offset = $img.offset(); // Offset from the corner of the page.
var xMargin = ($img.outerWidth() - $img.width()) / 2;
var yMargin = ($img.outerHeight() - $img.height()) / 2;
// Note that the above calculations assume your left margin is
// equal to your right margin, top to bottom, etc. and the same
// for borders.
var x = (ev.clientX + xMargin) - offset.left;
var y = (ev.clientY + yMargin) - offset.top;
alert('clicked at x: ' + x + ', y: ' + y);
});
});
</script>
Source: Stackoverflow.com