Home > database >  Add a function on focus and remove it on blur
Add a function on focus and remove it on blur

Time:04-06

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 refference 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>

CodePudding user response:

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>

CodePudding user response:

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>

CodePudding user response:

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);
          };
      };
      });
  • Related