Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top