Altjen B. Altjen B. - 22 days ago 10
ASP.NET (C#) Question

how to change the cssclass of a div after press a button in asp.net c#?

I am trying to change the background of a div after clicking a button. this are the codes.
Div I want to change color:

<div id="example1" runat="server">

</div>


and CSS for it:

#example1 {
position: absolute;
z-index: 5;
top:0;
background-color: orange;
width: 310px;
height: 34px;
color: white;

border-radius: 4px;
}


I want to change it to this:

#example2 {
position: absolute;
z-index: 5;
top:0;
background-color: red;
width: 380px;
height: 38px;
color: white;

border-radius: 4px;
}


I tried to write some code at Page.aspx.cs

example1.CssClass = "example2";


but looks like CssClass is not a function of the div. how can I add it? or whats a way to do it on C#?

Answer

You don't have to go back to server, in order to change the color of your div. This can be done solely on client by writing a simple script:

var example1 = document.getElementById("example1");

example1.addEventListener("click", function(){
    example1.className = "example2";
});
.example2 {
    position: absolute;
    z-index: 5;
    top:0;
    background-color: red;
    width: 380px;
    height: 38px;
    color: white;

    border-radius: 4px;
}
<div id="example1" runat="server">
  sample text
</div>

Important Note

In your case, since your div is a server side control, (runat="server"), the id that is generated before the page is sent to the client is not example1. So in the script I presented above we have to make a change:

var example1 = document.getElementById("<%= example1.ClientID%>");