Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I handle a right click event on an HTML <button /> element?

I've seen plenty of questions and answers on SO and elsewhere that talk about right click events and how to catch and handle them with JavaScript, generally using the .button attribute of the event object generated by the browser.

However, the one thing I haven't found, probably because it's a pretty weird request, is how to catch and handle right clicks on an HTML <button /> element. Buttons are not handled the same way by the browser as other elements. Most importantly, it seems that a right click on a button doesn't do anything. No context menu and, from what I can tell, no event.

Am I wrong? I hope so, because it will make my life easier. If not, I can simulate a button with a div and some CSS, but I'd rather avoid it. Any thoughts?

(PS: This is for a silly side project, so don't worry about me trying to put a button-right-click-based interface in front of any customers or anything. I'm well aware of how horrible that interface would probably be.)

like image 566
Ken Bellows Avatar asked Jul 25 '13 13:07

Ken Bellows


People also ask

Can we use Onclick in button tag?

The onclick attribute is an event attribute that is supported by all browsers. It appears when the user clicks on a button element. If you want to make a button onclick, you need to add the onclick event attribute to the <button> element.

How do you handle button click events?

Onclick in XML layout When the user clicks a button, the Button object receives an on-click event. To make click event work add android:onClick attribute to the Button element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event.

How does HTML detect right click?

Ya, though w3c says the right click can be detected by the click event, onClick is not triggered through right click in usual browsers. In fact, right click only trigger onMouseDown onMouseUp and onContextMenu. Thus, you can regard "onContextMenu" as the right click event.

Which HTML event let us click on the button?

The onclick event occurs when the user clicks on an element.


1 Answers

Sure, just add a onmousedown listener, check which mouse was pressed:

JS:

document.getElementById("test").onmousedown = function(event) {
    if (event.which == 3) {
        alert("right clicked!");
    }
}

HTML:

<button id="test">Test</button>

Demo: http://jsfiddle.net/Jmmqz/

like image 86
tymeJV Avatar answered Sep 30 '22 03:09

tymeJV