Skip to content

Instantly share code, notes, and snippets.

@jeffreyiacono
Created March 18, 2012 04:53
Show Gist options
  • Save jeffreyiacono/2069000 to your computer and use it in GitHub Desktop.
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
/**
* 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);
}
@tessro
Copy link

tessro commented Mar 19, 2012

Nice polyfill! If you want to be definitely insane and possibly awesome, you can overwrite mousedown to do this for you:

(function() {
  var originalFilter = $.event.fixHooks.mousedown.filter;

  var funkytown = function(event, original) {
    event = originalFilter(event, original);

    if(!event.offsetX) {
      event.offsetX = (event.pageX - $(event.target).offset().left);
      event.offsetY = (event.pageY - $(event.target).offset().top);
    }

    return event;
  }

  jQuery.event.fixHooks.mousedown.filter = funkytown;
}());

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.

@yukulele
Copy link

firefox have layerXand 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