Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

230
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda