Return to Snippet

Revision: 44551
at April 14, 2011 02:12 by wizard04


Initial Code
//returns event.button in both the W3C and Microsoft models
//in IE lte 8, a button combination (like 3==left+right) returns -1
function button(evt)
{
	evt = evt || window.event;
	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};
};

Initial URL


Initial Description
Returns an object with the `event.button` values of both the W3C and Microsoft models.

Initial Title
Mouse Event Button

Initial Tags
javascript, event, button

Initial Language
JavaScript