Apply/Change CSS dynamicaly using Javascript



This article consists of a sequence of screenshots depicting how CSS can be toggled dynamicaly using javascript. The CSS of the element is changed dynamicaly 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.

<div id="dvMessage">
Please enter your valid user name and password.
</div>
<
asp:Button Text="Toggle CSS" runat="server" ID="btnChange" OnClientClick="javascript:changeCSSClass('dvMessage');return false;" />


2. When 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.

.Error
{
font-family:Times New Roman Baltic;
font-size:13;
color:Red;
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.

.Warning
{
font-family:Calibri;
font-size:11;
color:Orange;
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.

<script language="javascript" type="text/javascript">
    function changeCSSClass(divId) {
        if (document.getElementById(divId).className == 'Error') {
            document.getElementById(divId).className = 'Warning';
        }
        else {
            document.getElementById(divId).className = 'Error';
        }

    }
</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.

<asp:Button Text="Toggle CSS" runat="server" ID="btnChange" OnClientClick="javascript:changeCSSClass('dvMessage');return false;" />

erver'>
Up Next
    Ebook Download
    View all
    Learn
    View all