1

I'm making a game, it uses the canvas element, and I need both of the mouse buttons. How can I stop the browser (I'd like it to run in most major ones, so, it's preferred that the solution is universal) from opening that dialogue box when the user presses the right mouse button. How can I do that in JavaScript? I tried this, but it does not work:

self.onClick = function(ev)
{
    if(ev.button == 2)
    {
        ev.preventDefault();
    }

    var x = ev.clientX - self.canvas.offsetLeft;
    var y = ev.clientY - self.canvas.offsetTop;
    input.mouse = {"button": ev.button, "click": true, "x": x, "y": y};
}

The global variable input is then sent to the server to be processed.

EDIT: it works now. I had to edit the canvas element (canvas oncontextmenu="return false")

corazza
  • 31,222
  • 37
  • 115
  • 186
  • Also, for anyone that really wants to know, I'm using Chrome to test stuff. – corazza Sep 23 '11 at 20:58
  • possible duplicate of [How to disable mouse right click on a web page?](http://stackoverflow.com/questions/3083798/how-to-disable-mouse-right-click-on-a-web-page) – JJJ Sep 23 '11 at 21:03

3 Answers3

2

You can try this:

self.oncontextmenu = function() {
    return false;
};
Jordão
  • 55,340
  • 13
  • 112
  • 144
2

Use self.oncontextmenu and call preventDefault on the event.

self.oncontextmenu = function(e) {
  e.preventDefault();
}

Note that some users may not like you disabling their context menu.

Digital Plane
  • 37,354
  • 7
  • 57
  • 59
2

It is onclick and not onClick

In this case use

self.oncontextmenu=function() { return false }

or

self.oncontextmenu=function(e) { e.preventDefault(); }

in plain JS

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Strange, this doesn't work. I'm using the newest version of Chrome for Linux. – corazza Sep 23 '11 at 21:53
  • And the difference between this and the accepted answer is what??? and looking at your update, it looks like my first suggestion. – mplungjan Sep 24 '11 at 17:03
  • Well all the answers I got are the same, but I can't accept them all. I did give you one ups and stuff... – corazza Sep 26 '11 at 15:10
  • they may be the same, but they were answered at different times and I also explained a typo you had. Never mind... – mplungjan Sep 26 '11 at 17:18