kapj jumarang
kapj jumarang

Reputation: 25

Eventlistener for right click

Is there a keycode for right click in javascript because here is what I was trying to do:

    document.addEventListener('keydown', event => {
        if (event.keyCode === 2) { //Right Mouse
            alert("Oh-NO!!");
        }
    });

Upvotes: 1

Views: 2175

Answers (1)

Brian Peacock
Brian Peacock

Reputation: 1849

You need to add a mousedown event rather than a keydown event. This will return an event.button property, the value of which will tell you which button was clicked...

$('element').addEventListener('mousedown', clicked, false);

function clicked(e) {
    switch (e.button) {
        case 0:
          // left mouse button
          break;
        case 1:
          // middle mouse button
          break;
        default:
          // 2 === right mouse button
    }
}

For right- and middle-clicks you may need to preventDefault behaviours.

Hope that helped :)

Upvotes: 1

Related Questions