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

293
Visualizações
Is there a simpler way to write this if/else statement without a variable?

I have a quiz with one input. On the first enter press, it grades the answer. On the second enter press, it resets a new question.

  1. Is there a simpler way to write this without the flip variable?

  2. If not, is there a way to include the variable inside so that I could export the function as a whole?

var flip = true;

document.getElementById("guess-input").addEventListener("keyup", (event) => {
  if (event.key === "Enter") {
    event.preventDefault();
    if (flip === true) {
      flip = false;
      check();
    } else {
      flip = true;
      reset();
    }
  }
});
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can use a data-attribute or a class

document.getElementById("guess-input").addEventListener("keyup", (event) => {
  if (event.key === "Enter") {
    event.preventDefault();
    const tgt = event.target;
    if (tgt.matches(".flipped")) check();
    else reset();
    tgt.classList.toggle("flipped")
  }
});
about 4 years ago · Juan Pablo Isaza Relatório

0

We can have some fun with it and set a new listener at the end of the first one, while making our listeners run only once.

const input = document.getElementById("guess-input") // to keep it neat
const options = {once: true}

function checker(e){
  if (e.key !== 'Enter') return
  e.preventDefault();
  check();
  input.addEventListener('keyup', resetter, options);
}

function resetter(e) {
  if (e.key !== 'Enter') return
  e.preventDefault();
  reset();
  input.addEventListener('keyup', checker, options);
}

input.addEventListener("keyup", checker, options)

You can also do it by reassigning the onkeyup handler which overwrites the original callback:

const input = document.getElementById("guess-input") // to keep it neat

function checker(e){
  if (e.key !== 'Enter') return
  e.preventDefault();
  check();
  input.onkeyup = resetter;
}

function resetter(e) {
  if (e.key !== 'Enter') return
  e.preventDefault();
  reset();
  input.onkeyup = checker;
}

input.onkeyup = checker;

This is just a different approach to the problem. The data attribute approach is perfectly valid.

about 4 years ago · Juan Pablo Isaza Relatório

0

If you wanted to keep the code the same you could use a closure - essentially move your variable inside the function but have that function return a new function that the listener calls when the event is triggered. This works because the returned function carries with it references to its "outer lexical environment" which, in this case, is the flip variable.

export default function guesser() {
  let flip = true;
  return function (event) {
    if (event.key === "Enter") {
      event.preventDefault();
      if (flip === true) {
        flip = false;
        check();
      } else {
        flip = true;
        reset();
      }
    }
  }
});

And then in your main code:

import guesser from './guesser';

const el = document.getElementById('guess-input');

// Call the guesser function which returns that inner
// function which the listener calls when the event is triggered
el.addEventListener('keyup', guesser());
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