user2811882 user2811882 - 3 months ago 18
Javascript Question

Disable Right Click Context Menu?

This tool increments the value at strength on left click at the value of strength and decrements the value on left click.

This works, however the context menu appears when you do a right click to decrement the value.

How can I get rid of it?

CODE AND DEMO



var Alexander =
{
Strength: "AlexanderStrengthVal",
Bonus: "AlexanderRemainingBonusVal",
Limits: {
Strength: 60,
}
};

function add(character, stat)
{
var txtNumber = document.getElementById(character[stat]);
var newNumber = parseInt(txtNumber.value) + 1;
var BonusVal = document.getElementById(character["Bonus"]);
if(BonusVal.value == 0) return;
var newBonus = parseInt(BonusVal.value) - 1;
BonusVal.value = newBonus;
txtNumber.value = newNumber;
}

function subtract(character, stat)
{
var txtNumber = document.getElementById(character[stat]);
var newNumber = parseInt(txtNumber.value) - 1;
if(newNumber < character.Limits[stat]) return;
var BonusVal = document.getElementById(character["Bonus"]);
var newBonus = parseInt(BonusVal.value) + 1;
BonusVal.value = newBonus;
txtNumber.value = newNumber;
}

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<table cellpadding='5' border='1' style="text-align:center; color:#ffffff; background-color:#444444; font-family:arial; font-size:14px">
<tr>
<td><b>Character</b></td>
<td><b>Strength</b></td>
<td><b>Spending Bonus</b></td>
</tr>
<tr>
<td>Alexander</td>
<td>
<input
id="AlexanderStrengthVal"
type="text" value="60"
style="width:30px; border:none; color:#ffffff; background-color:transparent; text-align:center"
onfocus="this.blur()"
onClick="add(Alexander, 'Strength')"
onContextMenu="subtract(Alexander, 'Strength');"
/>
</td>

<td>
<input
id="AlexanderRemainingBonusVal"
type="text"
value="30"
style="width:30px; border:none; color:#ffffff; background-color:transparent; text-align:center"
/>
</td>

</tr>
</table>
</body>
</html>




Answer

You will have to use event.preventDefault() to prevent that to happen.

In the case of your code, you have to pass the triggering event object as a reference to your function subtract. Like so:

onContextMenu="subtract(event, Alexander, 'Strength');" // This is in the HTML

function subtract(e, character, stat)
{
  e.preventDefault();
  // The rest of your codeā€¦
}

Working example

But please, note that your code is a mess. For one thing, in JSBin itself it outputs a series of warnings you should look into. For another thing, you shouldn't bind your event handlers inline. Please separate your concerns.