Article

Detect which mouse button clicked using JavaScript

In this article we will learn how to Detect which mouse button clicked using JavaScript.

JavaScript Event Object
event here is used for which properties of the event object are used to determine which mouse button is clicked by you.

Internet Explorer 8 and previous version use event.button property

For Left Button : 1
For Middle Button : 4
For Right Button : 2

Internet Explorer 9 and above version use event.which property

For Left Button : 1
For Middle Button : 2
For Right Button : 3

Write this following code to Detect which mouse button clicked using JavaScript.
JavaScript Code
[php]
<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>

<script type="text/javascript">
function whichMouseButtonClicked(event) {
var whichButton;
if (event.which) {
switch (event.which) {
case 1: whichButton = "Left Button Clicked"; break;
case 2: whichButton = "Middle Button Clicked"; break;
case 3: whichButton = "Right Button Clicked"; break;
default: whichButton = "Invalid Button Clicked"; break;
}
}
else {
switch (event.button) {
case 1: whichButton = "Left Button Clicked"; break;
case 4: whichButton = "Middle Button Clicked"; break;
case 2: whichButton = "Right Button Clicked"; break;
default: whichButton = "Invalid Button Clicked"; break;
}
}

document.getElementById(‘divShowResult’).innerHTML = whichButton;
}
</script>
<style>
#divShowResult {
height: 200px;
width: 200px;
padding: 10px;
margin: 10px;
display: inline-block;
background: #ff9900;

}

</style>
</head>
<body>
<label>Click this box</label>
<br /><br />
<div id="divShowResult" onmouseup="whichMouseButtonClicked(event)"></div>
</body>
</html>
[/php]
Output
detect-which-mouse-button-clicked-using-javascript
detect-which-mouse-button-clicked-using-javascript
detect-which-mouse-button-clicked-using-javascript

Leave a Reply

Your email address will not be published.