CancelImage Upload

How to detect which mouse button has been pressed with JavaScript

When developing an interactive web application with a windows like user interface you may need to know when a mouse button has been pressed, and when it has, which one.

To solve this little mystery we can consult the JavaScript event object, which will then in turn tell us which button has been clicked, left or right. It will do this by returning a number. On all browsers the number 2 means that the right button has been pressed. However, the left button will be represented by a 1 on internet explorer, while it will be a 0 on all other browsers. The middle button on the other hand will be a 4 on internet explorer and a 1 on all other browsers.


Here is how this code can be used in the real world. Most mice now days have done away with the middle button anyway, so you can now simply detect whether or not the right or left hand button has been pressed:

<title>Detecting which mouse button has been pressed with JavaScript</title>
<script type="text/javascript">

function getMouseButton(event)

       var status = document.getElementById("status");

       if(event.button == 2)

              status.innerHTML = "The right mouse button has been pressed.";


              status.innerHTML = "The left mouse button has been pressed.";




<body onmousedown="javascript:getMouseButton(event);">

<span id="status"></span>


Want to leave a comment?

No problem. Just enter your email and password below.

register | home | reminder

myDesignTool Networking •