When we build a web application, a few times we do not want the users to use the right button of the mouse. Today, many of the code examples used to disable the right-click no longer work in most browsers and browsers such as Opera do not allow the right-mouse button to be disabled. In addition to this issue, disabling the right-click can cause serious accessibility issues and often only angers users.
However there are many ways to disable right click. Here we are discussing 5ย of the most common ways to disable right click on your web application using jQuery or JavaScript.
Disable right click using jquery or javascript
Using JavaScript
We can call a function which will return false for oncontextmenu event of the HTML element for which we want to disable right click. Mostly it will be the body element because we want to disable right click on whole area of page.
1 2 3 | <body oncontextmenu="return false"> YOUR PAGE CONTENT HERE! </body> |
ย NOTE: oncontextmenu event is not supported in some browsers. So we should be careful about its use.
We can write it as follows
1 2 3 | document.addEventListener("contextmenu", function(e){ e.preventDefault(); }, false); |
By capturing mousedown event, We can also disable right click of mouse :
1 2 3 4 5 6 7 8 9 10 11 | <script language="javascript"> document.onmousedown=disableclick; function disableclick(event) { if(event.button==2) { alert("Right Click Disabled"); return false; } } </script> |
Using jQuery
1 2 3 4 5 | <script language="javascript"> $(document).on('contextmenu', function() { return false; }); </script> |
Another way by capturing mousedown/mouseup event:
1 2 3 4 5 6 7 8 9 10 11 12 | <script language="javascript"> $(document).on({ "mousedown": function(e) { console.log("normal mouse down:", e.which); e.preventDefault(); }, "mouseup": function(e) { console.log("normal mouse up:", e.which); e.preventDefault(); } }); </script> |
These are all 5 ways to disable right click using jQuery or JavaScript but keep in mind, disabling right click isn’t security, it’s just annoying your users.