Suliman Sharif Suliman Sharif - 1 year ago 54
Javascript Question

grab both the right and the left clicks of a user simultaneously

So my problem is this,

I was wondering if there was a way to detect if a user right clicks and left clicks simultaneously and commit an action if doing so in jQuery. It seems like the code can only detect one right click or one left click at a time in mouse events.

UPDATE

Thanks for the answers, I decided ultimately that feature would be too funky to have for users when I was trying to implement it. Hopefully these answers will be able to help other people too.

Answer Source

You can create variables to hold the state of each mouse button individually and use that to determine whether both buttons are down:

window.isLeftMouseDown = false;
window.isRightMouseDown = false;

$(document).on('mousedown', function(e) {
  if (e.which == 1)
    window.isLeftMouseDown = true;
  else if (e.which == 3)
    window.isRightMouseDown = true;

  if (window.isLeftMouseDown && window.isRightMouseDown) {
    console.log('both down');
  }
});

$(document).on('mouseup', function(e) {
  if (e.which == 1)
    window.isLeftMouseDown = false;
  else if (e.which == 3)
    window.isRightMouseDown = false;
});

https://jsfiddle.net/2j151tpt/