Hide Label Automatically after some seconds using JavaScript

Introduction

Open Visual Studio and create new project and select Web template from the list and select ASP.NET Empty Web Application. Enter the name of your application and click on OK.

Right click on the project and select Add -> Web Form and name it as Home.aspx.

Now Drag and drop one TextBox, a button and a Label on the Home.aspx page.

Paste the following JavaScript function in the head section of the Home.aspx page.

  1. <script type="text/javascript">  
  2.     window.onload = function ()  
  3.     {  
  4.         var seconds = 5;  
  5.         setTimeout(function () {  
  6.             document.getElementById("<%=displaymessage.ClientID %>").style.display = "none";  
  7.     }, seconds * 1000);  
  8. };  
  9. </script>  

Here I am hiding the Label after 5 seconds. 

Below is the code to make the label visible when Submit Form button is clicked.
  1. protected void OnClickSubmitButton(object sender, EventArgs e)  
  2. {  
  3.    displaymessage.Visible = true;  
  4. }  

ASPX Page Code

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Home.aspx.cs" Inherits="HideLabelAutomatically.Home" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title>HideLabelAutomatically</title>  
  8.     <script type="text/javascript">  
  9.         window.onload = function ()  
  10.         {  
  11.             var seconds = 5;  
  12.             setTimeout(function () {  
  13.                 document.getElementById("<%=displaymessage.ClientID %>").style.display = "none";  
  14.         }, seconds * 1000);  
  15.     };  
  16.     </script>  
  17. </head>  
  18. <body>  
  19.     <form id="form1" runat="server">  
  20.         <div>  
  21.             Enter Name:  
  22.             <asp:TextBox ID="Name" runat="server" />  
  23.             <br />  
  24.             <br />  
  25.             <asp:Button ID="submitbutton" Text="Submit Form" runat="server" OnClick="OnClickSubmitButton" />  
  26.             <br />  
  27.             <br />  
  28.             <asp:Label ID="displaymessage" ForeColor="Green" Font-Bold="true" Text="Form has been submitted successfully." runat="server" Visible="false" />  
  29.         </div>  
  30.     </form>  
  31. </body>  
  32. </html>  
Output
 
 
Ebook Download
View all
Learn
View all