Add color to list


Hello everyone,

Today I will talk about a little query I received recently from a client.

He wanted a list of tasks in color!

The principle was simple: If a task is completed, it appears in green, if the task is not completed and has the highest priority (level (1) High), it must be displayed in red.

For once I tried to use JavaScript instead of starting in a custom development. It did not look that complicated!

Here is an overview of our task list.

To begin , we need to add a Content Editor Web Part to the page where the list is displayed. We must add ListViewWebPart below the list.

If we check the classes applied to the cells, we can see that the class used for a list of fields is the class’ ms-VB2 “. So we will recover all the cells of the page and test those whose class is “ms-VB2”. Then we will check the contents of each cell and apply the desired style if needed. If the task is finished (“Completed”), we apply the color “lightgreen” to the entire line. If the job status is important (“(1) High”) and not completed, we apply the color “red” to the line.

 <script language="javascript" type="text/javascript"> var x = document.getElementsByTagName("TD") var i=0; for (i=0;i<x.length;i++) { if (x[i].className=="ms-vb2") { if (x[i].innerHTML=="Completed") { x[i].parentNode.style.backgroundColor='lightgreen'; } if (x[i].innerHTML=="(1) High" && x[i].parentNode.style.backgroundColor!='lightgreen') { x[i].parentNode.style.backgroundColor='red'; } } } </script> 

Result:

A simple code to display the tasks in color!

This small code will look at the contents of each cell in the list and if it finds the corresponding text he applies the right color. But be careful, if you have “Completed” or “(1) High” as content of another field that will change color.

For further testing jQuery is necessary, I will perhaps talk about this in a future article.

Christopher.

Advertisements