Unfortunately no solution worked for me.
I found a good implementation here:
var target = e.target || e.srcElement,
rect = target.getBoundingClientRect(),
offsetX = e.clientX - rect.left,
offsetY = e.clientY - rect.top;
e.offsetX = offsetX;
e.offsetY = offsetY;
This question needs an updated answer.
First, as I mentioned in a comment, regarding all of the older answers using layerX
and layerY
:
"This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future."
(Source: developer.mozilla.org/en-US/docs/Web/API/UIEvent/layerX)
Second, I've discovered that when you console.log(event)
in Firefox, offsetX
and offsetY
show 0, but when you console.log(event.offsetX)
, it is not 0. So be careful because you may be being lied to.
This behavior is explained here:
Logging objects
Don't use
console.log(obj)
, useconsole.log(JSON.parse(JSON.stringify(obj)))
.This way you are sure you are seeing the value of obj at the moment you log it. Otherwise, many browsers provide a live view that constantly updates as values change. This may not be what you want.
(Also note that JSON.stringify()
will not do what you want here... It doesn't stringify the entire event object.)
But , what you will do if there is not layerX
,layerY
fields ?
var xe=e.offsetX,ye=e.offsetY;
if(!xe){
xe=e.clientX - $(e.target).offset().left;
}
if(!ye){
ye= e.clientY - $(e.target).offset().top;
}
If some still needs a solutions this one works perfect in Firefox:
var x = e.offsetX || e.originalEvent.layerX;
var y = e.offsetY || e.originalEvent.layerY;
From a JQuery bug tracker page - a nice polyfill is this:
var offX = (e.offsetX || e.pageX - $(e.target).offset().left);
.. where e is the event returned from a jquery event. Obviously, only if you've got Jquery already on your project, otherwise will have to do the offset()
stuff manually.
Try layerX, layerY
var x = (e.offsetX === undefined) ? e.layerX : e.offsetX;
var y = (e.offsetY === undefined) ? e.layerY : e.offsetY;
FIDDLE