When I got this urgent bugfix request I thought it was going to be hell, but fortunately, it turned out to be relatively easy.
When a mouseUp event is triggered, you can check which button has been pressed with the event.button
property (in some browsers event.which
, and which
also has different values from button
, but I’m just focused on Chrome atm).
Previously in Chrome, on a mouseMove event while a button was pressed, the event.button
property showed the integer for the clicked button (2
in the case of a right-click), but this was changed recently, and it now shows 0
, presumably as there is not button click, either up or down, at that moment in time. Without doing any research I’m going to take a punt that this is a better match for the spec, and it does make a certain amount of sense, if one can get over the inconvenience.
The simple answer is to set a flag when the mouseDown event is triggered:
|
targetElement.addEventListener('mouseDown', function(event){ isRightClick = true; }); |
N.B. Remember to declare the initial variable previously in a scope accessible to all of your mouse events.
Then in your mouseMove event, where previously you checked event.button == 2
, you can now check isRightClick
:
|
targetElement.addEventListener('mouseMove', function(event){ if isRightClick == true) { // Draw your rubber band, or zoom or whatever you wanted to do } }); |
And finally, don’t forget to toggle the flag off at the end of the mouse operation;
|
targetElement.addEventListener('mouseUp', function(event){ isRightClick = false; }); |
This has the added advantage that if you do care about x-browser compatibility and those browsers that prefer event.which,
you check for the relevant property only once, when mouseDown
, fires and subsequently only have to check isRightClick
during the mouseMove
event – and as mouseMove
can fire thousands of times, this is a tiny but worthwhile optimisation.
Frankly you should have been doing that anyway. My excuse is I didn’t write the application I’m working on, and the person who did is most definitely NOT a front-end developer!
This change was introduced recently, somewhere around Chrome version 60/61 as far as I can tell.