| |
| Cross-Browser Mouse Event Handling |
| © 2009-10, Martin Rinehart (last update: 20100807) |
| |
Normally one would go to Peter-Paul Koch's book or his quirksmode.org site for cross browser JavaScript programming. Sadly, the mouse event handling information there is quite out of date. This is an update.
function fixupMouse( event ) {
event = event || window.event;
var e = { event: event,
target: event.target ? event.target : event.srcElement,
which: event.which ? event.which :
( (event.button === 2) ? 3 : 1 ),
x: event.x ? event.x : event.clientX,
y: event.y ? event.y : event.clientY
}
return e;
}
fixupMouse() function:
function myClickHandler( event ) {
e = fixupMouse( event );
e.target is the object that responded to the mouse.e.which is 1 (left button) or 3 (right button)e.x and e.y are screen coordinates relative to the browser's client area. e.event, the host object that you can use to access other event properties.
e.target.id) and the value of e.which. Move events update the status bar, if there is one, with the latest location. Try them in any browsers you want to support. (Your author has tested MSIE 6, 7 and 8, recent Chrome, Firefox, Opera and Windows Safari, and, on Linux, Opera and Konqueror. Reports on others, especially telephones, are welcome—MartinRinehart at gmail dot com.)
<tag ... onmousedown='onMouseDown(event);'>
e.which === 65536 on the buttonless events (over, out, move). All the others report e.which === 1. Don't use e.which in a buttonless event handler.
fixupMouse() Explainedfunction fixupMouse( event ) { event = event || window.event; window.event which we use here if event is undefined.
var e = { event: event, target: event.target ? event.target : event.srcElement, event.target. MSIE returns event.srcElement, which this ternary picks if event.target doesn't exist.
which: event.which ? event.which : e.which === 1 .
( (event.button === 2) ? 3 : 1 ), event.button with 1 for the left, 2 for the right and 4 for the center. That's arguably better as you could sum them for multiple buttons pressed at the same time. But it's unarguably non-standard. Here we return 3 for the right button.
x: event.x ? event.x : event.clientX, event.x and event.y as the event's location relative to the top-left corner of the browser's client area. Firefox and MSIE return this in event.clientX and event.clientY.
y: event.y ? event.y : event.clientY return e; event.x for example) it's semi-standard; W3C should add it.