let's say I have
<div onmouseup="myfunction()">
</div>
But how would I know if left or right mouse button was clicked?
let's say I have
<div onmouseup="myfunction()">
</div>
But how would I know if left or right mouse button was clicked?
There are two properties for finding out which mouse button has been clicked: which
and button
. Please note that these properties don’t always work on a click event. To safely detect a mouse button you have to use the mousedown or mouseup events.
which
is an old Netscape property. which will give below values for mouse buttons.
Left button - 1
Middle button - 2
Right Button - 3
No problems, except its meager support (and the fact that it’s also used for key detection).
Now button has been fouled up beyond all recognition. According to W3C its values should be:
Left button – 0
Middle button – 1
Right button – 2
According to Microsoft its values should be:
Left button – 1
Middle button – 4
Right button – 2
No doubt the Microsoft model is better than W3C’s. 0 should mean “no button pressed”, anything else is illogical.
Besides, only in the Microsoft model button values can be combined, so that 5 would mean “left and middle button”. Not even Explorer 6 actually supports this yet, but in the W3C model such a combination is theoretically impossible: you can never know whether the left button was also clicked.
and to check which type of button is clicked always use feature detection for which
and button
properties
if (e.which) {
// old netsapce implementation
consoel.log((e.which == 3) + ' right click');
} else if (e.button) {
// for microsoft or W3C model implementation
consoel.log((e.button == 2) + ' right click');
}
Reference:
Checked this function:
function getEvt (evt) {
var mouseEvt = (evt).which;
var mMouseEvt = evt.button;
console.log(mouseEvt);
console.log(mMouseEvt);
}
It returns int. For example for left click:
1 listeners.js (line 43)
0 listeners.js (line 44)
function doSomething(e) {
var rightclick;
if (!e) var e = window.event;
if (e.which) rightclick = (e.which == 3);
else if (e.button) rightclick = (e.button == 2);
alert('Rightclick: ' + rightclick); // true or false
}