Get Image Coordinates With jQuery

Applications like PhotoShop make it easy to find the X,Y coordinates of points within an image. But, what about when you need to get that information from a user on your website? This script lets you grab the coordinate of any point of an image via jQuery (a free JavaScript library). In this example, we don't do anything with the coordinates except print them to the screen, but you could easily save them for use elsewhere.

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div><span id="image_coords_click"></span><span id="image_coords_now">&nbsp;</span></div>
<img id="image" src="../images/inkplant/code/penguin.jpg">
<script type="text/javascript">
  $('#image').mousemove( function(event) {
	window.current_x = Math.round(event.pageX - $('#image').offset().left);
	window.current_y = Math.round(event.pageY - $('#image').offset().top);
	window.current_coords = window.current_x + ', ' + window.current_y;
	$('#image_coords_now').html('Current: ' + window.current_coords + '.');
  }).mouseleave( function() {
	$('#image_coords_now').html('&nbsp;');
  }).click( function() {
	$('#image_coords_click').html('Last click: ' + window.current_coords + '. ');
  });
</script>

You can see a working example of the above code at our Image Coordinates tool. From there, you can also find the coordinates of your own image; it lets you swap the image out with your own.


Comments

Loading…

This post was published on September 22nd, 2014 by Robert James Reese in the following categories: Images, JavaScript, and jQuery. Before using any of the code or other content in this post, you must read and agree to our terms of use.