1

I want to disable the right click menu on a table. Because I'm using the rightclick to change the color of it (did a little Battleship game). However I did not found anything that still works. So I would really appreciate your answer :)

This is the call:

<td class="tdBox" onclick="attack(this, ${xStatus.count}, ${yStatus.count})" onmouseover="background(this)" onmouseout="backgroundLeave(this)" oncontextmenu="markField(this)">

and this is the JavaScript function:

function markField(obj) {
    obj.style.backgroundColor = 'blue';
    //return false;
}
2
  • looks like a partial dup of stackoverflow.com/questions/737022/… Commented Apr 18, 2016 at 6:10
  • Take the code from the link kay27 posted. In that replace alert(status); line by your colour change code. P.S. I would suggest to not use right click for your input however, as that is never a good idea on a web app. Commented Apr 18, 2016 at 6:21

2 Answers 2

2

Here's how to override the contextmenu event handler:

document.addEventListener("contextmenu", function(e) {
  e.preventDefault();
  alert('Right click');

  // Or, in you case: markField()
});

Note: using document is not a requirement. It will work on any DOM node. Alternatively, you can make the blockage conditional by checking the target of e.

Fiddle: https://jsfiddle.net/h1jdr1ew/1/

Sign up to request clarification or add additional context in comments.

2 Comments

This does work partly since I dont want to disable the rightclick on the whole site. However I found a solution based on this by using getElementsByClassName. function disableRightClick(){ var tdBox = document.getElementsByClassName("tdBox"); for (i = 0; i < tdBox.length; i++) { tdBox[i].addEventListener("contextmenu", function(e) { e.preventDefault(); }); } }
Yes, it will work on any DOM node, not just document.
0

Try this code

<script language="javascript">
function markField(obj)
{
  if(event.button==2)
   {
     //add your code here
     obj.style.backgroundColor = 'blue';
     return false;    
   }
}
</script>

<td class="tdBox" onclick="attack(this, ${xStatus.count}, ${yStatus.count})" 
onmouseover="background(this)" onmouseout="backgroundLeave(this)" 
oncontextmenu="markField(this)">

2 Comments

I have tried it with return false; but it did not work.
what is the error coming? Also, which browser? Some browser do not allow disabling right click. Edit: Check in console to see if JS throws an error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.