6

What is the difference between event.button and event.which in Javascript mouse events?

1
  • 1
    button for mouseDown and mouseUp, buttons for mouseMove, and don't use which
    – Bitterblue
    Nov 27, 2019 at 8:01

2 Answers 2

5

event.button

Indicates which mouse button caused the event.

event.which

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.

Difference

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
4
  • Hm yes, but both seem to indicate the mouse button - what exactly is the difference?
    – chopper
    Mar 17, 2014 at 22:30
  • Let me give you a further example. Mar 17, 2014 at 22:31
  • @chopper, I believe my last edit answers your question. Mar 17, 2014 at 22:33
  • Yes, specifically for the mouse events. For the keyboard events it normalizes event.keyCode and event.charCode. Mar 17, 2014 at 22:37
5

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.