Created
March 18, 2012 04:53
-
-
Save jeffreyiacono/2069000 to your computer and use it in GitHub Desktop.
simple normalization of jquery event so offsetX / offsetY can be used cross browsers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* normalizeEvent | |
* | |
* Firefox does not implement offsetX, OffsetY, so we have to detect for this an | |
* manually calculate it ourselves using the pageX, pageY less the event | |
* target's left offset and right offset | |
* | |
* If using a browser that supports offsetX, OffsetY, just return the event, | |
* don't need to do anything | |
*/ | |
var normalizeEvent = function(event) { | |
if(!event.offsetX) { | |
event.offsetX = (event.pageX - $(event.target).offset().left); | |
event.offsetY = (event.pageY - $(event.target).offset().top); | |
} | |
return event; | |
}; | |
LOLrus.prototype.someMethodThatDependsOnEventPosition = function() { | |
$(this._someIternalHtmlDomEl) | |
.unbind('click') | |
.mousedown(_.bind(function(e) { | |
e = normalizeEvent(e); | |
this._somethingThatWantsCurrentMouseDownPosition(e.offsetX, e.offsetY); | |
}, this); | |
} |
firefox have layerX
and layerY
value;
div.on('click',function(e) {
var x = (e.offsetX != null) ? e.offsetX : e.originalEvent.layerX;
var y = (e.offsetY != null) ? e.offsetY : e.originalEvent.layerY;
});
(event.pageX - $(event.target).offset().left);
method dont works with transformed elements (css3 rotate(), scale(), translate() ...)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice polyfill! If you want to be definitely insane and possibly awesome, you can overwrite mousedown to do this for you:
Of course, if you ship this code there is a 90% chance you will be struck by a car, and simultaneously by lightning, next time you cross the street.