javascript Change div color based on controller value

I have a div which is a circle within a circle. I want the outer ( class=”circle”) circle to change color based on value of a number. for instance, red if greater than 20, yellow if less than 10 and green if less than 5. Is this possible?

<apex:page controller="myController"
  <html>
   <body>
     <style type="text/css">
        .circle
        {
        width:150px;
        height:155px;
        border-radius:250px;
        font-size:50px;
        float:left;
        margin-left:1cm;
        border:1px solid black;;
        line-height:155px;
        text-align:center;
        background:#000
        }
        .circle2
        {
        width:120px;
        height:120px;
        border-radius:125px;
        font-size:50px;
        margin-left:0.4cm;
        margin-top:0.4cm;
        border:1px solid black;;
        line-height:155px;  
        background:white;
        }

      </style>


       <div id="circlecontainer" style="width:25%; margin-left:0.3cm; margin-top:0.3cm; height:155px; border:1px solid black; float:left; ">
        <div class="circle">
            <div class="circle2"> 
               <p style="margin-top:-0.5cm;"> {!queueCount}</p>  
            </div> 
        </div>   
       </div>
</body>
</html>
</apex:page>

Answer

I would create a method on your controller to expose the color value to the page in lieu of a complicated IF() or CASE() statement written directly in the page. You can use this value in the class attribute and apply a style to your circle div based on the value which was calculated in the controller.

public string getQueueCountColor() {
    if (queueCount < 5) {
        return 'green';
    } else if (queueCount < 10) {
        return 'yellow';
    } else if (queueCount > 20) {
        return 'red';
    } else {
        return 'somewhere_between_yellow_and_red';
    }
}

Page Markup

<style type="text/css">
    .red {
        background-color: red;
    }
    .yellow {
        background-color: yellow;
    }
    .green {
        background-color: green;
    }
</style>

<div id="circlecontainer" style="width:25%; margin-left:0.3cm; margin-top:0.3cm; height:155px; border:1px solid black; float:left; ">
    <div id="outerCircle" class="circle {!queueCountColor}">
        <div class="circle2"> 
            <p style="margin-top:-0.5cm;"> {!queueCount}</p>  
        </div> 
    </div>   
</div>

I just realized that it was requested to be done in JavaScript rather than directly in the page markup. This same style of mechanism can be employed with JavaScript Remoting and adding the returned value from the remoting call to the div element’s className attribute.

document.getElementById("outerCircle").className += theReturnedValue; etc.

Attribution
Source : Link , Question Author : Thomas Riddler , Answer Author : Mark Pond

Leave a Comment