Skip to content

Instantly share code, notes, and snippets.

@CatEntangler
Created December 28, 2015 05:34
Show Gist options
  • Save CatEntangler/f100c2c7e4b918165318 to your computer and use it in GitHub Desktop.
Save CatEntangler/f100c2c7e4b918165318 to your computer and use it in GitHub Desktop.
Get the coordinates of an image click in percentage. Helpful for responsive sites that have variably displayed images
$('img').on('click', function(event) {
var coordinates = get_click_coords(event);
});
function get_click_coords(event) {
var pos_x = event.offsetX ? (event.offsetX) : event.pageX - document.getElementsByTagName("img").offsetLeft;
var pos_y = event.offsetY ? (event.offsetY) : event.pageY - document.getElementsByTagName("img").offsetTop;
var percentage_x = ( pos_x / event.target.clientWidth ) * 100;
var percentage_y = ( pos_y / event.target.clientHeight ) * 100;
return {X: percentage_x, Y: percentage_y};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment