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

155
Visualizações
Add a function on focus and remove it on blur

I'm trying to set a simple script where, whenever you focus on an input and press Enter, something happens. Just like in those searchboxes on webpages and forums.

The problem is I can't make the function stop after the user clicks in a different place. I tried adding blur and it doesn't help, I get a

"Uncaught ReferenceError: pressEnter is not defined at HTMLInputElement."

Also tried to set the function as an individual one and call it later in the eventlistener BUT I can't pass the event argument for that function to work (I've just started studying EventListeners so, please, take it easy on me)

I'd appreciate any help on how to correctly reference the pressEnter function or any different solutions.

inputTest = document.querySelector("#test")


inputTest.addEventListener("focus", function pressEnter() {


    window.addEventListener("keyup", (e) => {
        if (e.key === "Enter") {
            console.log("Pressed")
        }
    })
})

inputTest.addEventListener("blur", () => {

    window.removeEventListener("keyup", pressEnter())
    console.log("Done(?)")

}
)
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Events</title>
</head>

<body>
    <input type="text" id="test">

    <script src="script.js"></script>
</body>

</html>

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

0

You don't need such a complicated "architecture" to achieve that functionality, you need just to add the keyup event listener directly to input element, like so:

const inputTest = document.querySelector("#test")

inputTest.addEventListener("keyup", (e) => {
    if (e.key === "Enter") {
        console.log("Pressed")
    }
});
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Events</title>
</head>

<body>
    <input type="text" id="test">

    <script src="script.js"></script>
</body>

</html>

about 4 years ago · Juan Pablo Isaza Relatório

0

Based on what you are trying to do you could replace your event listener with a form tag. If you are trying to implement something like a search bar this could be semantically correct. See if this works for you:

const handleSubmit = () => {
  const input = document.querySelector("#test");
  const inputValue = input.value;

  console.log(inputValue);

  // You can handle any logic here

  return false;
};
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Events</title>
  </head>

  <body>
    <form name="eventForm" onsubmit="handleSubmit()" action="#">
      <input type="text" id="test" />
    </form>

    <script src="script.js"></script>
  </body>
</html>

about 4 years ago · Juan Pablo Isaza Relatório

0

Searchboxes on webpages and forums simply detect a keyup on the current DOM. like the following.

// EnterkeyListener
  document.addEventListener('keyup' , function(e){

  if (e.key == "Enter") {
      const searchValue = document.querySelector("#test").value;
      console.log(searchValue);
  };
  });

and if you really want nothing should happen when the searchbar is empty then you can use a if statement like

    // EnterkeyListener
    document.addEventListener('keyup' , function(e){
    
      if (e.key == "Enter") {
          const searchValue = document.querySelector("#test").value;
   // check if searchbar has any value if so then run this code
          if (searchValue) {
            console.log("I have a value")  
            console.log(searchValue);
          } else {   //if not then run this code
            console.log("i don not have a value");
            console.log(searchValue);
          };
      };
      });
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