Aaron Salazar
Aaron Salazar

Reputation: 4527

Dynamically Changing HTML

I am trying to create a HTML page where the "body" color changes depending on some data being gathered from the RAM. If the RAM fills up beyond a certain threshold then I want the color to change.

    <body style="background-color:<%=
    if(MemoryPercentage < 33)
    {
        //set to green.
    }
    else if(MemoryPercentage < 66)
    {
        //set to yellow.
    }
    else
    {
            //set to red.
    }%>">

Thank you for your help,

Aaron

Upvotes: 0

Views: 277

Answers (4)

tadamson
tadamson

Reputation: 8851

Just an aside to the other answers:

<body id="Body" runat="server"> will make the tag accessible to Page_Load() & friends as an HtmlGenericControl, so you can handle the logic and set Body.CssClass without the template-y markup. Makes it a little less messy / easier to maintain.

Upvotes: 0

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68667

<body 
    style="background-color:<%= MemoryPercentage < 33? "green":
        (MemoryPercentage < 66? "yellow":"red") %>;">

Upvotes: 4

tvanfosson
tvanfosson

Reputation: 532435

I'd prefer using CSS classes and separating the logic out so it is more readable.

<style type="text/css">
.warn {
   background-color: #00ffff;
}
.error {
   background-color: #ff0000;
}
.ok {
   background-color: #00ff00;
}
</style>

<%
    var klass = MemoryPercentage < 33 : "ok" ? (MemoryPercentage < 66 ? "warn" : "error");
%>

<body class="<%= klass %>">

Upvotes: 4

casperOne
casperOne

Reputation: 74530

While you can definitely apply the style directly using the sytle attribute of the body tag (as suggested in this answer), general best practices revolving around HTML discourage this.

What you should do is place these styles in a stylesheet which is referenced on your page, and then have different names for the classes.

Then, in your code, apply the class that has the style you want depending on your logic to the class attribute of the body element.

Upvotes: 0

Related Questions