39

I'm writing aWebGL game and want to use right-click as a control. However, it throws up a menu. Is it possible to disable that? I've tried

} 
else if (event.which == 2 || event.which == 3) 
{
    doRightClickControl();
    event.preventDefault();
    event.stopPropagation();

    return false;
}

Thanks dknaack for the hint. I got it to work like this:

window.oncontextmenu = function(event) {
    event.preventDefault();
    event.stopPropagation();
    return false;
};
Chris
  • 6,642
  • 7
  • 42
  • 55

2 Answers2

34

Using jQuery for this purpose only is overkill. This will do the trick:

(function () {
  var blockContextMenu, myElement;

  blockContextMenu = function (evt) {
    evt.preventDefault();
  };

  myElement = document.querySelector('#myElement');
  myElement.addEventListener('contextmenu', blockContextMenu);
})();

myElement can be replaced with window.

bennedich
  • 12,150
  • 6
  • 33
  • 41
  • 1
    I actually ended up doing something like this, without pulling in JQuery. – Chris Oct 24 '11 at 18:35
  • 3
    And for the casual readers coming from Google, please don't do this unless you have a good reason. [Your users may despise your site](http://superuser.com/questions/279166/how-do-i-set-google-chrome-to-not-allow-javascript-to-hijack-my-right-click-menu). – Elias Dorneles Sep 10 '13 at 22:38
  • This doesn't work in Chrome 66 – basZero May 02 '18 at 09:29
  • Just what I wanted! I combined it into a single statement and added in that holding shift would let it pass through again. --- document.querySelector('html').addEventListener('contextmenu', function (evt) { if(!evt.shiftKey){ evt.preventDefault(); } }); – BoB3K May 09 '18 at 18:48
3

Use this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<head>
<title>disable rightclick menu - LabLogic</title>
</head>
<body>
<script language="javascript" type="text/javascript">
  document.oncontextmenu=RightMouseDown;
  document.onmousedown = mouseDown; 

  function mouseDown(e) {
      if (e.which==3) {//righClick
      alert("Disabled - do whatever you like here..");
   }
}
function RightMouseDown() { return false;}
</script>
</body>
</html>

Tested in chrome 17, works with other new browsers as well

LabLogic
  • 189
  • 1
  • 2
  • Worked fine in firefox and chrome but not working in internet explorer 8..tested it. Its showing Errors on Page and then error is : which is null or not an object..Please look into it..thanks btw :) – Sachin Jain Apr 09 '12 at 05:15