Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add eventlistener when user leaves input

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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">  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading