MattsBits
MattsBits

MattsBits

Colour Code List Cells In Sharepoint 2007  

by Matt Hawkins, 02/08/2011
Categories : Sharepoint

This JavaScript code can be used to colour code cells in a Sharepoint list.

The script works by looking at all the table cells on a page (ie <td> elements) and identifying the ones using the "ms-vb2" class. These are the cells used in standard lists.

It then checks the content of the cell and if it matches one of the conditions it changes the background colour of that cell.

In the example it looks for cells containing the colours "Green", "Amber" or "Red" and sets the background colour appropriately.

This could be modified to change other style sheet properties such as text colour, font weight etc.


<script type="text/javascript" language="javascript">
  var x = document.getElementsByTagName("TD");
  var i=0;
  for (i=0;i<x.length;i++)
  {

    if (x[i].className=="ms-vb2") //find the cells styled for lists
    {

      if (x[i].innerHTML=="Green") //find the data to use to determine the colour
      {
        x[i].style.backgroundColor="Green"; // set the colour
      }

      if (x[i].innerHTML=="Amber")
      {
        x[i].style.backgroundColor="Yellow"; // set the colour
      }

      if (x[i].innerHTML=="Red")
      {
        x[i].style.backgroundColor="Red"; // set the colour
      }

     }
  
  }

  // Finished updating cells

</script>


This script can be added to a Content Editor Webpart below the list you wish to colour code.

Group By Issue

Unfortunately it will not work if you use the "Group By" functionality in your View. Why? Because the table data isn't loaded until you expand a group so the above JavaScript does not get a chance to change the colours.

To solve this you should set your View to Group By as normal but set "show groupings" to "expanded". When the page loads all the data will be present and the cells will be coloured.

If you don't want all your groups expanded you can use the following jQuery to collapse the groups immediately after JavaScript has finished colour coding them.

$("img[src*='minus.gif']:visible").parent().click();


This should be placed just below the "Finished updating cells" comment in the JavaScript above.

It will require the jQuery library to be loaded in the <HEAD> of your page.

You can either download jQuery and host on your own site or grab it from Google's servers using :

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" 
        type="text/javascript"></script>

Author : Matt Hawkins  Last Edit By : Matt Hawkins
PHP Powered  MySQL Powered  Valid XHTML 1.0  Valid CSS  Firefox - Take Back The Web  EUKHost - Recommended Webhosting Solutions

MattHawkins CMS v3.0 - Copyright 2009-2017