I have disabled right click in my application using the following:
<body oncontextmenu="return false;">
I have a textarea element which has spellcheck enabled. I want to be able to right-click in this field (for spellcheck) but I want right-click to be disabled everywhere else in the app.
I have done the following:
<textarea onfocus="rightclickon()" onblur="rightclickoff()" spellcheck="true"></textarea>
These are the functions:
function rightclickon() {
$('body').prop('oncontextmenu', 'null');
}//end rightclickon
function rightclickoff() {
$('body').prop('oncontextmenu', 'return false');
}//end rightclickoff
My logic behind the above is that whenever the user enters the textarea, right-click would be enabled but when they leave the field, it would be disabled again. This does not work how I expected.
The first part works (right-click is enabled when the ueser enters the field). However, when the field is left, right-click does not get disabled again. It just remains on.
Is their an easier way to achieve what I want?
Simply inspect the origin of the event and decide what to do accordingly
document.addEventListener('contextmenu', function(e) {
if (!e.target.matches('textarea')) {
e.preventDefault()
}
}, false)
<p>Some paragraph</p>
<ul>
<li>List 1</li>
<li>List 2</li>
<li>List 3</li>
</ul>
<textarea>Just try right-clicking in here</textarea>
<p>Another paragraph</p>
See https://developer.mozilla.org/en/docs/Web/API/Element/matches for details about Element.matches