Created
May 6, 2012 04:09
-
-
Save bbogovich/2611313 to your computer and use it in GitHub Desktop.
JavaScript mouse event handler example to compensate for Firefox's lack of offsetX/offsetY
This file contains hidden or 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
| /* | |
| * addClickEvent(HTMLElement ele, Function(x,y) callback) | |
| * | |
| * Invokes the function "callback" when element "ele" is clicked, passing the | |
| * x,y coordinate of the click event to the callback function. The coordinates | |
| * are relative to the top-left corner of the element. | |
| */ | |
| function addClickEvent(ele,callback){ | |
| /* | |
| * click(Event e) | |
| * Gecko browsers do not support the offsetX and offsetY properties on mouse events. | |
| * Backtrack to the top-level element to calculate the offset values. | |
| */ | |
| function click(e){ | |
| var x=0,y=0; | |
| if(typeof(e.offsetX)=="undefined"||typeof(e.offsetY)=="undefined") { | |
| var mozLeft=e.clientX; | |
| var mozTop=e.clientY; | |
| var target=e.target; | |
| mozLeft = mozLeft - target.offsetLeft; | |
| mozTop = mozTop - target.offsetTop; | |
| var parent = target.offsetParent; | |
| while(parent){ | |
| mozLeft = mozLeft - parent.offsetLeft; | |
| mozTop = mozTop - parent.offsetTop; | |
| parent = parent.offsetParent; | |
| } | |
| x = mozLeft; | |
| y = mozTop; | |
| }else{ | |
| x=e.offsetX; | |
| y=e.offsetY; | |
| } | |
| callback(x,y); | |
| } | |
| if(ele.addEventListener){ /* IE9+, Everything Else */ | |
| ele.addEventListener("click",click,false); | |
| } else if(ele.attachEvent){ /* IE 5-8 */ | |
| ele.attachEvent("onclick",click) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment