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.

event.button

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:

<html>
<head>
<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.";

       }
       else
       {

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

       }

}

</script>
</head>

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

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

</body>
</html>


Login
Want to leave a comment?

No problem. Just enter your email and password below.


register | home | reminder

myDesignTool Networking • www.mydesigntool.cominfo@mydesigntool.com