views:

60

answers:

2

Right let’s get this out the way first. Yes, I want to hide the context menu. No, I’m not trying to prevent someone lifting content off my page. Its intended use is input for an in-browser game and it will be limited to a specific area on the webpage.

Moving from the ideological to the technical...

var mouse_input = function (evt) {
    // ...
    return false;
}

document.onmousedown = mouse_input; // successful at preventing the menu.
document.addEventListener('mousedown', mouse_input, true); // unsuccessful

Could someone explain to me why the addEventListener version is unable to stop the context menu from firing? The only difference I was able to see in Safari's Web Inspector was that document.onmousedown had a isAttribute value that was true whilst the addEventListener version had the same value as false.

A: 

So my unfruitful search suddenly became fruitful.

var mouse_input = function (evt) {
    evt.preventDefault();
}

document.addEventListener('contextmenu', mouse_input, false);

Works for Safari, Firefox, Opera. preventDefault() stops the usual actions from happening. I had to change the event that was listened for to accommodate for Safari and it is more logical anyway. Further information: functions that implement EventListener shouldn’t return values so return false had no effect.

casr
Yes, that's the way to do it. It won't work in IE, though: in IE, you'll need to use `attachEvent` and set `window.event.returnValue` to `false`.
Tim Down
Thanks for the info. I’m targeting browsers with `<canvas>` support and fortunately I believe IE9 has both that and `addEventListener`.
casr
Yes, that's true. Fair enough.
Tim Down
A: 

To explain the difference .. element.onmousedown = somefunction; is an absolute assignment; you are replacing the event handler on the element. element.addEventListener(...) is, as the name implies, adding a handler in addition to any handler(s) already attached for the event.

Stephen P