function myFunction() {
if(rock == true){console.log("dd")}
}
<div class="overview">
<div class="userSide">
<h4>User:</h4><span> </span>
<img id="userImg" src="img/Paper.png" style="width: 220px; height: 220px;">
</div>
<div class="compSide">
<h4>CPU:</h4><span> </span>
<img id="compImg" src="img/Paper.png" style="width: 220px; height: 220px;">
</div>
</div>
<div class="userBTN">
<button id="rock" onclick="myFunction()">Rock</button>
<button id="paper" onclick="myFunction()">Paper</button>
<button id="scissors" onclick="myFunction()">Scissors</button>
</div>
One easy way... make your function take an argument like:
function myFunction(whichOne) {
if(whichOne == "rock"){console.log("dd")}
}
and then call each with the right value:
<div class="userBTN">
<button id="rock" onclick="myFunction('rock')">Rock</button>
<button id="paper" onclick="myFunction('paper')">Paper</button>
<button id="scissors" onclick="myFunction('scissors')">Scissors</button>
</div>
You could do it like the following:
window.onload = () => {
const clickHandler = (e) => {
switch (e.target.dataset.rps) {
case "rock":
console.log('🗿');
break;
case "paper":
console.log('📃');
break;
case "scissors":
console.log('✂️');
break;
default:
console.log('undefined');
}
};
document.querySelectorAll('button[data-rps]').forEach(it => it.addEventListener('click', clickHandler));
}
<div class="userBTN">
<button data-rps="rock">Rock</button>
<button data-rps="paper">Paper</button>
<button data-rps="scissors">Scissors</button>
</div>
I feel working with the data-attribute instead of the id is better when working with this kind of functionality. Because you are not limited to a specific id. Basically, you could copy that component and place it somewhere else and it would still work.
In this specific case, you only have to manage 3 ids, but if you want to extend functionality it is easy to quickly add another data-attribute instead (in general) and you don't have to rebuild the logic, because it uses the same dataset again.
Besides, you can avoid adding the onClick handler three times and use a more general selector to produce clean html and avoid boilerplate code.
The provided data-attribute data-rps can then be used to determine the type.
e.target refers to the event target, which is the element that has triggered the onClick-event.
add a data-attribute.
https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
<button data-name="rock" id="rock" onclick="myFunction">rock</button>
...
and you can check if selected with:
function myFunction(event) {
if (event.target.dataset.name === "rock") {
// do something......
}
}
Or you could check for it's ID.
if (event.target.id === 'rock') {
// do something
}
But it looks semantically more clean if you give it a data attribute if you look at the HTML file.