| | Stumble It! | Add to Mixx! | | diigo it | | Slashdot |

Friday, July 31, 2009

Color Coding Dates in SharePoint Lists - Part 2

Thanks to a comment from Jen on the Part 1 post, I've updated this code as well! This code is easier to work with and understand so it should be much easier to implement. As usual, you'll need to add the Content Editor Web Part to the bottom of the page and then add this code to the "Source Editor..." section:
<script type="text/javascript">
// Change these variables to suit your needs
var dateCols = ['Due Date','Date Completed']; // add Column Titles to the "dateCols" array to color code those columns
var green = 7; // tasks this many days out will be green
var blue = 3; // tasks that are this many days or more are blue
var red = 1; // tasks due in this many days are red
// end user variables
//
var tbls = document.getElementsByTagName("TABLE");
var col = new Array();
for (var t in tbls) {
if (tbls[t].className == "ms-listviewtable") {
var rows = tbls[t].childNodes[0].childNodes;
var hRow = rows[0].getElementsByTagName("TH");
for (i=0;i<hRow.length;i++) {
col[i] = (hRow[i].innerText || hRow[i].textContent) + "";
col[i] = col[i].replace(/\n/,"");
}
for (r=1;r<rows.length;r++) {
for (c=0;c<col.length;c++) {
for (d=0;d<dateCols.length;d++) {
if (col[c] == dateCols[d]) {
colorIt(rows[r].childNodes[c],green,blue,red);
}
}
}
}
}
}
//
function colorIt(x,green,blue,red) {
var strDate = x.innerText || x.textContent;
var today = new Date();
var dateDiff = ((Date.parse(strDate) - Date.parse(today)) / 86400000);
if (dateDiff > green) {
x.innerHTML = "<div style='color:green;'>"+x.innerHTML+"</div>";
} else if (dateDiff >= blue) {
x.innerHTML = "<div style='color:blue;'>"+x.innerHTML+"</div>";
} else if (dateDiff > red) {
x.innerHTML = "<div style='color:red;'>"+x.innerHTML+"</div>";
} else if (dateDiff <= red) {
x.innerHTML = "<div style='color:red;text-decoration:line-through;'>"+x.innerHTML+"</div>";
}
}
</script>

4 comments:

rozentals said...

Script is great, thanks.
But I found it is not working in list view with 'Group by' enabled.

AWizardInDallas said...

That's because the table headers are gone. Is there another way to get the elements of the table?

Thien said...

I tried the script you provided exactly as you have it but it did not work. I tried your script from part 1, that did work when I was in edit mode but as I exited edit mode the color coding went away.

What am I doing wrong?

Asif @ SharePoint said...

Hello Ben,
You are great! This is one of the best workaround (for the functionalities that are not possible in SharePoint OOB)that I have ever seen.
But,the problem in the code is - This does not work if the "Regional settings" are changed to any other than US.
Please let me know if you have any solution on this.

Thanks,
Asif