1. Technology

JavaScript By Example

Events: 10. Which Mouse Button

By

There are not as many instances now where working out which of the three mouse buttons was the one pressed is actually useful as there used to be. The common use of testing the mouse button pressed to block access to the context menu no longer works in modern browsers.

Unlike early browsers such as Netscape 4 which had their own set of codes to identify the different mouse buttons, all modern browsers use the same eight values to indicate which of the three buttons are pressed ranging from 0 meaning no buttons pressed through 7 to indicate that all three are pressed.

In this example code we have a function that splits the value into three separate integers where 1 indicates that the specified button is pressed and 0 identifies that it is not. As with the last few examples we return an object with a separate property for each mouse button.


whichButton = function(event) {
var left, right, middle, b;
b = event.button;
middle = Math.floor(b/4);
b %= 4;
right = Math.floor(b/2);
left = b%2;
return {'left' : left, 'right': right, 'middle': middle};
};

  1. About.com
  2. Technology
  3. JavaScript
  4. Javascript Tutorials
  5. JavaScript By Example
  6. Events
  7. JavaScript By Example - Events: Which Mouse Button

©2014 About.com. All rights reserved.