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

420
Visualizações
How to Create a button to execute code when pressing enter or clicking the button?

I have created a button. right now the button only works after clicking the button. what I want to do is, When I press the 'enter' key on the keyboard or click the button my code needs to be executed.

how to do that?

const befoClick= document.querySelector('.befoClick');
const afteClick=document.querySelector('.afteClick');

befoClick.addEventListener('click',()=>{
    afteClick.classList.toggle('clicked'); 
 });
body{
  display: grid;
  place-items: center;
  height:100vh;  
}

button{
  width:200px;
  height:50px;
  font-size:20px;
  cursor: pointer;
  border:none;
   border-radius: 8px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); 
}
.befoClick{
  background-color: rgb(74, 74, 255);
}

.afteClick{
   background-color: rgb(67, 255, 77);
  visibility: hidden;
}

.clicked{
    visibility: visible;
}

.bfrClick{
    visibility: hidden;
}
<div class='allBtn'>
<div >
  <button class='befoClick'>CLICK ME</button>
  </div>
<div >
  <button class='afteClick'>CLICKED</button>
  </div>
  
  </div>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Use the keyup event listener and then check the pressed key.

There are two event listeners so, I added a separate function.

const befoClick= document.querySelector('.befoClick');
const afteClick=document.querySelector('.afteClick');

const toggleClass = () => afteClick.classList.toggle('clicked'); 

befoClick.addEventListener('click', toggleClass);
 
document.addEventListener('keyup', (event) => {
  if (event.key === 'Enter') {
    toggleClass();
  }
});
body{
  display: grid;
  place-items: center;
  height:100vh;  
}

button{
  width:200px;
  height:50px;
  font-size:20px;
  cursor: pointer;
  border:none;
   border-radius: 8px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); 
}
.befoClick{
  background-color: rgb(74, 74, 255);
}

.afteClick{
   background-color: rgb(67, 255, 77);
  visibility: hidden;
}

.clicked{
    visibility: visible;
}

.bfrClick{
    visibility: hidden;
}
<div class='allBtn'>
<div >
  <button class='befoClick'>CLICK ME</button>
  </div>
<div >
  <button class='afteClick'>CLICKED</button>
  </div>
  
  </div>

about 4 years ago · Juan Pablo Isaza Relatório

0

we can use an array like ['click', 'keyup] and then use forEach on the array to listen to both Events with the same eventListener.

However, if you use Enter it will trigger the eventListener twice as it recognizes the click and the Enter press itself. As such we need to run the script then also twice.

Then in the actual script, you can use classList.toggle to toggle between a clicked class to apply style changes.

Then you can toggle the textContent of the button between an array aswell.

var eleButton = document.querySelector('.button'),
  buttonText = ['CLICK ME', 'CLICKED'],
  indexButtonText = 0;

['click', 'keyup'].forEach(el => {
  eleButton.addEventListener(el, function(e) {
    changeButton();
    if (e.key == 'Enter') {
      changeButton();
    }
  });
});

function changeButton() {
  indexButtonText = (indexButtonText == 0 ? 1 : 0);
  eleButton.classList.toggle('clicked');
  eleButton.textContent = buttonText[indexButtonText];
}
body {
  display: grid;
  place-items: center;
  height: 100vh;
}

button {
  width: 200px;
  height: 50px;
  font-size: 20px;
  cursor: pointer;
  border: none;
  border-radius: 8px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgb(74, 74, 255);
}

.clicked {
  background-color: rgb(67, 255, 77);
}
<button class='button'>CLICK ME</button>

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