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
You need input event, not focus.
And get value by
e.target.value
.Declare
x
inside of the event listener to update the variable each time:Just replace
focus
withkeyup
so it will always detect when you type. Also putx
insidemyFunction3
to get an updated value.