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

308
Vistas
javascript addeventlistener passing the codes to execute for shorter code

Is there a way that I can shorten this code. They have similar condition but different codes to execute. the first one is when I keydown the element will show or hide, the second one after I click the button or submit the form, it will stop or pass the user.

textInput.addEventListener("keydown", function myFunction(){
  if(textInput.value.match(characters)){
    invalidFeedback.style.display = "block";
  }
  else if (textInput.value === ""){
    invalidFeedback.style.display = "block";
  } else {
    invalidFeedback.style.display = "none";
  }
});


form.addEventListener("submit", function (event, myFunction){
  if(textInput.value.match(characters)){
    event.preventDefault();
  }
  else if (textInput.value === ""){
    event.preventDefault();
  }
});
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

When multiple conditional statements have the same outcome, we can use the || operator, which is like "OR".

We can also export common checks to functions, to keep things granular, neat, and easy-to-consume.

Finally, in the "keydown" event, I introduced a guard clause, which returns the desired outcome on a satisfied condition. It's much easier to read than nested if/else statements.

const doesMatch = () => textInput.value.match(characters);
const isEmpty = () => textInput.value === "";

textInput.addEventListener("keydown", () => {
  if (doesMatch() || isEmpty()) 
    return invalidFeedback.style.display = "block";
  invalidFeedback.style.display = "none"; 
});

form.addEventListener("submit", (event) => {
  if (doesMatch() || isEmpty()) event.preventDefault();
});
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