Disabling contextmenuwith an event handler
I am trying to disable the right click on an element. I found a solution that does it like this:
<div oncontextmenu='return false'></div>
But since this is not a good practice for event handlers in html, I tried something like:
<div id='test'></div>
and in the js part of the code:
let test = document.getElementById('test')
test.addEventListener('contextmenu', (e) => {
console.log('right click!')
return false
})
let test2 = document.getElementById('test2')
test2.addEventListener('contextmenu', (e) => {
console.log('right click!')
return false
})
div {
height: 100px;
width: 100px;
border: 1px solid black;
}
#test1 {
background-color: red;
}
#test2 {
background-color: blue;
}
<div id='test1' oncontextmenu='return false'></div>
<div id='test2'></div>
Run codeHide resultRight-clicking on it test1will be successfully disabled, but not on test2, and the console will prove that the program control has reached the handler.
I'm not looking for a workaround like
<div id='test'></div>
let test = document.getElementById('test')
test.addEventListener('contextmenu', (e) => {
e.preventDefault()
console.log('right click!')
})
works great.
I want to know why the two elements in the above snippet behave differently?
source
share