/ Published in: JavaScript
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
//position values of a mouse event //usage: var pos = new MousePosition(mouse_event); function MousePosition(evt) { this.screen = { x: evt.screenX, y: evt.screenY }; this.window = this.frame = { x: evt.clientX, y: evt.clientY }; if(isNaN(evt.pageX) || isNaN(evt.pageY)) { //scroll position of document var left, top; if(window.pageYOffset) //all except IE { left = window.pageXOffset; top = window.pageYOffset; } else if(document.documentElement && !isNaN(document.documentElement.scrollTop)) //IE standards compliance mode { left = document.documentElement.scrollLeft; top = document.documentElement.scrollTop; } else //IE quirks mode { left = document.body.scrollLeft; top = document.body.scrollTop; } this.document = { x: left + evt.clientX, y: top + evt.clientY }; } else { this.document = { x: evt.pageX, y: evt.pageY }; } this.layer = { x: evt.layerX || evt.x, y: evt.layerY || evt.y }; } //returns event.button in both the W3C and Microsoft models //in IE lte 8, a button combination (like 3==left+right) returns -1 for the W3C model function mouseButton(evt) { var ms, w3c; //in the W3C model, 0==left, 1==middle, 2==right //in the Microsoft model, 1==left, 4==middle, 2==right if(evt.which) { w3c = evt.which - 1; ms = evt.which == 1 ? 1 /*left*/ : evt.which == 2 ? 4 /*middle*/ : 2 /*right*/; } else //IE lte 8 { ms = evt.button; //actually, this would need to be: evt.button & !previous_evt_button //otherwise, if evt.button == 3 (for example), it could be either the left or the right button //since we can't reliably keep track of the previous evt.button, we will use -1 for the w3c value // if ms is not 1, 4, or 2 w3c = ms == 1 ? 0 /*left*/ : ms == 4 ? 1 /*middle*/ : ms == 2 ? 2 /*right*/ : -1 /*unknown*/; } return {w3c: w3c, ms: ms}; };