Click an image to calculate the pointer position inside the image. Using getBoundingClientRect() with clientX/clientY works reliably even when the page is scrolled.
$( "#coordinate-image" ).on(
"click",
function ( event ) {
const rect =
this.getBoundingClientRect();
const x = Math.round(
event.clientX - rect.left
);
const y = Math.round(
event.clientY - rect.top
);
$( "#coordinate-result" ).text(
"X: " + x + ", Y: " + y
);
}
);
The old pageX - offsetLeft pattern can be wrong when offset parents or scrolling are involved.
Original image-coordinate demo →
← jQuery Events · Pointer coordinates
<script>
$(document).ready(function() {
$("img").on("click", function(event) {
var x = event.pageX - this.offsetLeft;
var y = event.pageY - this.offsetTop;
$('#d1').html("X Coordinate: " + x + ", Y Coordinate: " + y )
});
});
</script>
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.