Left and right mouse click in javascript

What is the best way to capture left and right click in javascript? I do not use jQuery (it is next on my training list), just javascript for now. Basically, I want to do something like

 onClick()=javascript:rightClickFunction() // do right click function
 onContextMenu()=javascript:leftClickFunction() /
 onBoth() ???

The only thing I could find in stackoverflow was: How to distinguish left and right mouse button from jQuery

How do I double click on a button? Can I check if the opposite button is pressed during the procedures of the R and L buttons?

+3
source share
2 answers

You can track which mouse buttons are omitted with some logical variables, such as:

var leftButtonDown = false;
var rightButtonDown = false;

$(document).mousedown(function() {
    if(e.which == 1) {
        leftButtonDown = true;
    } else if (e.which == 3) {
        rightButtonDown = true;
    }
});

$(document).mouseup(function() {
    if(e.which == 1) {
        leftButtonDown = false;
    } else if (e.which == 3) {
        rightButtonDown = false;
    }
});

$(document).click(function() {
    if(leftButtonDown && rightButtonDown) {
        // left and right buttons are clicked at the same time
    }
});

If both boolean values ​​are true, the right and left mouse buttons are pressed.

+10

Pure Javascript, :

var leftButtonDown = false;
var rightButtonDown = false;

document.addEventListener("mousedown", function () {
    if (e.which == 1) {
        leftButtonDown = true;
    } else if (e.which == 3) {
        rightButtonDown = true;
    }
});

document.addEventListener("mouseup", function () {
    if (e.which == 1) {
        leftButtonDown = false;
    } else if (e.which == 3) {
        rightButtonDown = false;
    }
});

document.addEventListener("click", function () {
    if (leftButtonDown && rightButtonDown) {
        // Click with both LMB and RMB.
    }
});
0

All Articles