Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect right click + left click

I am building a game

And I need to do something when the user clicks on the right mouse button, holds it and then presses the left button

How can I detect this behaviour?

like image 867
Harman met Avatar asked Mar 13 '23 23:03

Harman met


2 Answers

JSfiddle: https://jsfiddle.net/mkarajohn/pd725ch6/5/

var rightMouseClicked = false;

function handleMouseDown(e) {
  //e.button describes the mouse button that was clicked
  // 0 is left, 1 is middle, 2 is right
  if (e.button === 2) {
    rightMouseClicked = true;
  } else if (e.button === 0) {  
    //Do something if left button was clicked and right button is still pressed
    if (rightMouseClicked) {
      console.log('hello');
      //code
    }
  }
  console.log(rightMouseClicked);
}

function handleMouseUp(e) {
  if (e.button === 2) {
    rightMouseClicked = false;
  }
  console.log(rightMouseClicked);
}

document.addEventListener('mousedown', handleMouseDown);
document.addEventListener('mouseup', handleMouseUp);
document.addEventListener('contextmenu', function(e) {
    e.preventDefault();
});
like image 130
Dimitris Karagiannis Avatar answered Mar 23 '23 15:03

Dimitris Karagiannis


Use MouseEvent.buttons in your event handler.

<element>.addEventListener("mousedown", function(event){
    if ((event.buttons & 3) === 3){
        //Do something here
    }
}, true);

It is kinda recent though, you may want to implement fallback method, recording state of mouse buttons.

like image 43
weaknespase Avatar answered Mar 23 '23 14:03

weaknespase