? I've seen a lot of questions and answers on SO and other places that talk about r...">

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

I've seen a lot of questions and answers on SO and other places that talk about right-click events and how to catch and process them using JavaScript, usually using the .button attribute of the .button object generated by the browser.

However, one thing I did not find, probably because this is a rather strange request, is how to catch and handle right-clicks on the HTML <button /> element. Buttons are not handled by the browser in the same way as other elements. Most importantly, it seems that right-clicking on a button does nothing. There is no context menu and, as far as I can tell, no event.

Am I really wrong? I hope so because it makes my life easier. If not, I can simulate a button with a div and some CSS, but I would prefer to avoid this. Any thoughts?

(PS: This is for stupid third-party projects, so don't worry about trying to put the right-click interface in front of any clients or anything else. I know very well how awful the interface will probably be.)

+6
source share
4 answers

Of course, just add the onmousedown , check which mouse was clicked:

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/

+10
source

http://jsfiddle.net/jqYN5/ is this what you are looking for? Adding context-menu :

 <input type="button" value="click me" id="btn"> <button id="btn2">right click</button>` 
 document.getElementById('btn').onclick = function() { alert('click!') } document.getElementById('btn2').oncontextmenu = function() { alert('right click!') } 
+5
source

You can also use the "context menu":

 document.getElementById('btn2').oncontextmenu = function() { alert('right click!') } 
0
source

Or perhaps a slightly more understandable understanding of the beginner level:

 <script type="text/javascript"> function mouseclick(ele, e) { if (e.type == 'click') { alert('Left Click Detected!'); } if (e.type == 'contextmenu') { alert('Right Click Detected!'); } } </script> <a href="/" onclick="mouseclick(this, event)" oncontextmenu="mouseclick(this, event)" >link name</a> 
0
source

Source: https://habr.com/ru/post/950268/


All Articles