I'm new to js and today i was writing a simple script to check placeholder of the input text, if input text is clicked it removes placeholder, and if user leaves input empty, it turns placeholder back. problem is can't find an eventlistener when user leaves the input. how can i check when user leaves input?
let element = document.getElementById("username");
const x = () => {
element.setAttribute("placeholder"," ");
}
element.addEventListener("click",x);
const y = () => {
if(element.value === ""){
element.setAttribute("placeholder", "USERNAME");
}
}
<input type="text" placeholder="USERNAME" name="username" id="username">
CodePudding user response:
You can create an eventListener
with focusout
event, and then set the value of your placeholder
as you wish.
let element = document.getElementById("username");
const x = () => {
element.setAttribute("placeholder"," ");
}
element.addEventListener("click",x);
const y = () => {
if(element.value === ""){
element.setAttribute("placeholder", "USERNAME");
}
}
element.addEventListener("mouseout", function(){
element.placeholder = "new placeholder";
})
<input type="text" placeholder="USERNAME" name="username" id="username">
CodePudding user response:
you can check when user focuses out of the input by putting eventlistener focusout :
element.addEventListener("focusout", y);
just add this at bottom of your codes and it'll work fine.