Reza
Reza

Reputation: 3919

How to correctly handle right click mouse event for a button

I want to handle mouse right-click event for my button. I wrote the following code;

mybutton.onmousedown = e => {
    e.preventDefault();
    const mouseEvent = { 
        0: () => leftClickCallback,
        2: () => rightClickCallback
    }
    mouseEvent[ e.button ]();
}

It works fine but it doesn't prevent the browser context menu and I have to set the "oncontextmenu" event like below to prevent the browser context menu event;

mybutton.oncontextmenu = e => e.preventDefault();

I've also tried to stop propagation of mouse event like below although it didn't work:

mybutton.onmousedown = e => {
        e.preventDefault();
        e.stopPropagation(); // <====
        const mouseEvent = { 
            0: () => leftClickCallback,
            2: () => rightClickCallback
        }
        mouseEvent[ e.button ]();
}

I am wondring why I need to explicitly disable oncontextmenu event for my button.

Upvotes: 3

Views: 2311

Answers (1)

Seblor
Seblor

Reputation: 7136

The right mouse button click seems to fire multiple events (though it might depend on the browser) :

  • a MouseDown event, with event.button === 2 and/or event.which === 3,
  • a ContextMenu event.

It makes sense since the context menu can also be opened by a keyboard button (depending on your keyboard layout), or a macro.

What you can do is use the same callback. For example :

function preventAll(event) {
    event.preventDefault();
    event.stopPropagation();
}

document.getElementById('something').addEventListener('mousedown', preventAll);
document.getElementById('something').addEventListener('contextmenu', preventAll);
<button id="something">test</button>

Upvotes: 3

Related Questions