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;
}
Selias
  • 47
  • 1
  • 8
  • looks like a partial dup of http://stackoverflow.com/questions/737022/how-do-i-disable-right-click-on-my-web-page – kay27 Apr 18 '16 at 06: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. – jitendragarg Apr 18 '16 at 06:21

2 Answers2

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/

Nicklas Nygren
  • 2,595
  • 13
  • 19
  • 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(); }); } }` – Selias Apr 18 '16 at 12:19
  • Yes, it will work on any DOM node, not just `document`. – Nicklas Nygren Apr 18 '16 at 12:19
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)">
jitendragarg
  • 945
  • 1
  • 14
  • 54