skip to Main Content

I made an input with a paragraph position absolute to the input element.

I just want to hide the element when the input value is not empty and display it when the input value is empty.

This is the code I wrote but it’s not working. What should I do please. Thanks.

var x = document.getElementById("searchBtn").value;

document.getElementById("searchBtn").addEventListener("focus", myFunction3);

function myFunction3() {
  if (x == "") {
    document.querySelector(".mypara").style.visibility = "visible";
  } else {
    document.querySelector(".mypara").style.visibility = "hidden";
  }

}
<input id="searchBtn">
<div class="mypara">mypara</div>

3

Answers


  1. You need input event, not focus.

    And get value by e.target.value.

    document.getElementById("searchBtn").addEventListener("input", myFunction3);
    
    function myFunction3(e) {
      let x = e.target.value
      document.querySelector(".mypara").style.visibility = x === "" ? "visible" : "hidden";
    }
    <input id="searchBtn">
    <div class="mypara">mypara</div>
    Login or Signup to reply.
  2. Declare x inside of the event listener to update the variable each time:

    document.getElementById("searchBtn").addEventListener("focus", myFunction3);
    
    function myFunction3() {
      var x = document.getElementById("searchBtn").value;
      if (x == "") {
        document.querySelector(".mypara").style.visibility = "visible";
      } else {
        document.querySelector(".mypara").style.visibility = "hidden";
      }
    
    }
    <input id="searchBtn">
    <div class="mypara">mypara</div>
    Login or Signup to reply.
  3. Just replace focus with keyup so it will always detect when you type. Also put x inside myFunction3 to get an updated value.

    document.getElementById("searchBtn").addEventListener("keyup", function(e) {
      var x = e.target.value;
      document.querySelector(".mypara").style.visibility = x == "" ? "visible" : "hidden";
    });
    <input id="searchBtn">
    <div class="mypara">mypara</div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search