I need to disable contextmenu
only inside a specific div #wrapper
and its children, and not the whole page. This is what I’m doing:
JavaScript
x
7
1
document.addEventListener('contextmenu', function (event) {
2
console.log(event.target.id);
3
if (event.target.id === 'wrapper') {
4
event.preventDefault();
5
}
6
});
7
.. but it doesn’t seem to work.
Advertisement
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:
JavaScript
1
6
1
var myWrapper = document.getElementById('wrapper');
2
3
myWrapper.addEventListener('contextmenu', function(e) {
4
e.preventDefault();
5
}, true);
6