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?
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();
});
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.
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