user3463147
user3463147

Reputation: 45

How to display a message for a few seconds and then disappear in javascript

The following is a code snippet for successful username entry. It checks the value from the database and displays message accordingly. I want to display the else part only for a few seconds i.e. "Username successful" message should show and disappear.

if(xmlhttp.responseText==1)
{
    document.getElementById("check").innerHTML="Username already exists";
}
else
{
    document.getElementById("check").innerHTML="Username successfull";          
}

The check class is as follows:

<ul class="user">
    <li class="label">User name </li>
    <li class="field">
        <input type="text" id="username" name="username" class="required error" onchange="checkuser(this.value);"/> 
       <div class="check " id="check"/>
    </li>
</ul>

Upvotes: 4

Views: 13849

Answers (1)

laaposto
laaposto

Reputation: 12213

You can use setTimeout so that after a period of time you want to change Usernane successfull to an emptry string

Try:

if(xmlhttp.responseText==1)
        {
          document.getElementById("check").innerHTML="Username already exists";
        }
        else
        {
         document.getElementById("check").innerHTML="Username successfull";
         //ADD THIS CODE
         setTimeout(function(){
         document.getElementById("check").innerHTML="";
         },3000);

        }
    }

Or you can change the display attribute after period of time you want again with setTimeout

Try:

if(xmlhttp.responseText==1)
            {
              document.getElementById("check").innerHTML="Username already exists";
            }
            else
            {
             document.getElementById("check").innerHTML="Username successfull";
             //ADD THIS CODE
             setTimeout(function(){
             document.getElementById('check').style.display = "none";
             },3000);

            }
        }

Upvotes: 7

Related Questions