Disable contextmenu for a specific container and its children

Tags:



I need to disable contextmenu only inside a specific div #wrapperand its children, and not the whole page. This is what I’m doing:

document.addEventListener('contextmenu', function (event) {
    console.log(event.target.id);
    if (event.target.id === 'wrapper') {
        event.preventDefault();
    }
});

.. but it doesn’t seem to work.

Answer

You’re approaching this the wrong way: you’re adding the listener to the document, which may be ok, but it’s easier to add it to the element itself, and you are checking event.target.id, which is the ID of the current clicked element (e.g. a children of your wrapper), not the wrapper.

To make this work you can easily do something like this instead:

var myWrapper = document.getElementById('wrapper');

myWrapper.addEventListener('contextmenu', function(e) {
    e.preventDefault();
}, true);


Source: stackoverflow