Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`return false` in an event handler attached by addEventListener or element.on*

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.

like image 876
casr Avatar asked Feb 27 '23 11:02

casr


1 Answers

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.

like image 54
casr Avatar answered Apr 27 '23 15:04

casr