Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

242
Vistas
How to check if a button is clicked inside an if statement?

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>
I have one function on 3 buttons and want the function to analyze which button was clicked than perform a task. Is this possible or do I have to add 3 separate functions?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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>
about 4 years ago · Juan Pablo Isaza Denunciar

0

Solution

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>

data-attribute vs id

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.

using the onclick-event

e.target refers to the event target, which is the element that has triggered the onClick-event.

about 4 years ago · Juan Pablo Isaza Denunciar

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda