Apply/Change CSS dynamicaly using Javascript

Introduction

 
This article consists of a sequence of screenshots depicting how CSS can be toggled dynamically using javascript. The CSS of the element is changed dynamically using javascript.
 
1. No CSS yet applied
 
CSS1.gif
 
The following are the HTML elements that create the preceding page when the page is being run.
  1.  <div id="dvMessage">  
  2. Please enter your valid user name and password.  
  3. </div>  
  4. <asp:Button Text="Toggle CSS" runat="server" ID="btnChange" OnClientClick="javascript:changeCSSClass('dvMessage');return false;" /> 
2. When the user clicks the Toggle CSS button for the first time
 
CSS2.gif
 
The following is the CSS applied to the <div> element when the user clicks the Toggle CSS button.
  1. .Error  
  2. {  
  3. font-family:Times New Roman Baltic;  
  4. font-size:13;  
  5. color:Red;  
  6. height:30px;  

3. When the user clicks the Toggle CSS button for the second time
 
CSS3.gif
 
The Following is the CSS applied to the <div> element when the user clicks the Toggle CSS button.
  1. .Warning  
  2. {  
  3. font-family:Calibri;  
  4. font-size:11;  
  5. color:Orange;  
  6. height:30px;  

How to apply/change CSS dynamically?

 
The following is the Javascript function that accepts a parameter and then gets the id of the element and compares the name of the class using className property and depending on the value it assigns a new value to the element.
  1. <script language="javascript" type="text/javascript">  
  2.     function changeCSSClass(divId) {  
  3.         if (document.getElementById(divId).className == 'Error') {  
  4.             document.getElementById(divId).className = 'Warning';  
  5.         }  
  6.         else {  
  7.             document.getElementById(divId).className = 'Error';  
  8.         }  
  9.   
  10.     }  
  11. </script> 
The preceding function is called on the client click event of the button as shown below. After calling the function "return false;" is written, the reason for this is that the page does not do a postback. If you remove the "return false;" statement the page will start doing a postback when the user clicks the Toggle CSS button and the page will not retain the dynamically assigned CSS class.
  1. <asp:Button Text="Toggle CSS" runat="server" ID="btnChange" OnClientClick="javascript:changeCSSClass('dvMessage');return false;" />  


Similar Articles