RuDee
RuDee

Reputation: 11

Disabling right click contextmenu with trigger to enable it back

I want to be able to disable the right click menu on my website, which I'm doing with the following:

document.addEventListener("contextmenu", function(e){e.preventDefault(); }, false);

How would I re-enable right clicking, such as when the user clicks on a button elsewhere on the page? Maybe something like

function() {
  $('body').unbind();
}

Thanks, the code below works great:

HTML

<div class="listener">
    <button onclick="stopjs()" id="stop">Stop</button>
</div>

JavaScript code

function prevent(e) {
    console.log('preventing');
    e.preventDefault();
}

document.addEventListener("contextmenu", prevent);

function stopjs() {
    document.removeEventListener("contextmenu", prevent);
}

Upvotes: 0

Views: 685

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370999

You'll have to save a reference to the function you pass into addEventListener, and then you'll be able to remove it later:

function prevent(e) {
  console.log('preventing');
  e.preventDefault();
}
document.addEventListener("contextmenu", prevent);

setTimeout(() => {
  document.removeEventListener("contextmenu", prevent);
}, 3000);

Upvotes: 2

Related Questions