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

156
Visualizações
How to toggle the content of an element by pressing a key?

Im currently trying to make a website where if i press q the p tag will change from "Q" to "A". This currently works with the code below. However the problem is that when pressing q it needs to go back to "A". I've tried making it work with removeEventListeners but it doesn't seem to work.

<script>
    document.addEventListener("keypress", event => {
        if (event.key == "q") {
            document.getElementById("P1").innerText = "Q"
        }
    });
</script>
almost 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Like @diegod suggested in the comments you should check which character is currently shown in the p element and change the innerText accordingly:

const p1 = document.getElementById("P1");

document.addEventListener("keypress", event => {
  if (event.key == "q") {
    if (p1.innerText == "A") {
      p1.innerText = "Q";
    } else {
      p1.innerText = "A";
    }
  }
});

Using ternary operator example:

const p1 = document.getElementById("P1");

document.addEventListener("keypress", event => {
  if (event.key == "q") {
    p1.innerText = p1.innerText == "A" ? "Q" : "A";
  }
});
almost 4 years ago · Santiago Trujillo Relatório

0


const $ = (prop) => document.querySelector(prop)

const changeToQ = () => {
  $('p').innerText = 'Q'
}

const reset = () => {
  $('p').innerText = 'A'
}

document.addEventListener('keydown', (e) => {
  if (e.key === 'q') changeToQ()
})

document.addEventListener('keyup', (e) => {
  if (e.key === 'q') reset()
})

I think this is what are you looking for

almost 4 years ago · Santiago Trujillo Relatório

0

have your tried to make else statement

else{ document.getElementById("P1").innerText = "A"}
almost 4 years ago · Santiago Trujillo 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