-1

I have an element (a div) that is 100px wide and 30px high. I would like to calculate where on this element did the user click. For example if the click right in the middle of it I would like to get 50 for x coordinate and 15 for y coordinate. The values returned need to be relative to the element itself not the page or the parent.

Is this doable with JavaScript or JQuery?

Marko
  • 12,543
  • 10
  • 48
  • 58
  • `HTML`
    `script` $("#something").click(function(e){ var parentOffset = $(this).parent().offset(); //or $(this).offset(); if you really just want the current element's offset var relX = e.pageX - parentOffset.left; var relY = e.pageY - parentOffset.top; alert('relX: '+ relX + ' ,relY: '+ relY); }); >**[demo](http://jsfiddle.net/7o2849fq/)**
    – ozil Apr 10 '15 at 14:32

1 Answers1

2

The event which is passed to the jQuery handler contains the co-ordinates of the click event relevant to the parent DOMElement within the offsetX and offsetY properties. Try this:

$('#foo').click(function (e){
    console.log(e.offsetX, e.offsetY);
});

Example fiddle

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339