O'Reilly logo

JavaScript & DHTML Cookbook by Danny Goodman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Determining Which Mouse Button Was Pressed

NN 6, IE 4

Problem

You want your event handler function to read which mouse button or button combination was used for a click-related mouse event.

Solution

Both the IE and W3C DOM event models agree that the button property of the event object is the one that holds information about the button or buttons used to generate a mousedown event (button values don't always come with mouseup or click events). Unfortunately, this is where the similarity ends.

Some of the integer values associated with the button property differ between the two event models. But they do agree that a value of 2 means that the right (nondominant) mouse button was used for the event. Here is a template for an event handler function that branches into separate processing paths for the right button and all other buttons:

 function myFunction(evt) {
    evt = (evt) ? evt : ((window.event) ? event : null);
    if (evt) {
        if (typeof evt.button != "undefined") {
            if (evt.button =  = 2) {
                // process right-click here
                return false;
            } else {
                // process all other clicks here
            }
        }
    }
}

Discussion

The reason that the example function tests for the presence of the button property is for the sake of graceful degrading with Navigator 4, which has an entirely different property and value range for the mouse button information. The property is called which, and the value for the right button is 3. If you need to support Navigator 4, you can rework the skeletal structure in the Solution to accommodate ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required