What is the difference between event.button
and event.which
in Javascript mouse events?
mouseup: mouseup event occurs when button of the mouse is released over an element. The name of the event handler is onmousedup. mousedown: mousedown event occurs when button of the mouse is pressed over an element. The name of the event handler is onmousedown. mousemove: mousemove event occurs when button of the mouse move over an element.
The event object passed to the mouse event handler has a property called button that indicates which mouse button was pressed on the mouse to trigger the event. 0: the main mouse button pressed, usually the left button. 1: the auxiliary button pressed, usually the middle button or the wheel button.
click: click event occurs when mouse is clicked on the register element. The name of the event handler is onclick. mouseup: mouseup event occurs when button of the mouse is released over an element. The name of the event handler is onmousedup. mousedown: mousedown event occurs when button of the mouse is pressed over an element.
0: the main mouse button pressed, usually the left button. 1: the auxiliary button pressed, usually the middle button or the wheel button. 2: the secondary button pressed, usually the right button. 3: the fourth button pressed, usually the Browser Back button. 4: the fifth button pressed, usually the Browser Forward button.
Indicates which mouse button caused the event.
According to jQuery's documentation:
...event.which also normalizes button presses (mousedown and mouseupevents), reporting 1 for left button, 2 for middle, and 3 for right. Use event.which instead of event.button.
In all modern browsers (IE8+) event.button
will give you the following values:
0 Specifies the left mouse-button
1 Specifies the middle mouse-button
2 Specifies the right mouse-button
While in IE8 and earlier:
1 Specifies the left mouse-button
4 Specifies the middle mouse-button
2 Specifies the right mouse-button
event.which
standardize these results by providing you the following values:
1 Specifies the left mouse-button
2 Specifies the middle mouse-button
3 Specifies the right mouse-button
I'm relatively shy to the last solution despite my upvote. According to the MDN documentation :
This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future
So, MouseEvent.button is still prefered. An interesting (case) alternative could be MouseEvent.buttons which permits you to determine all buttons pressed when the event is triggered.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With