Friday 21 May 2010

Color coding List item based on date

We had a need to maintain a set of books as library. I decided to go with SharePoint list with 'Issued Date' as DateTime column and 'Due Date' column as calculated column (Issued Date + 14 days).
The formula for 'Due Date' is =[Issued Date]+14

Added one more column of type 'Yes\No' with name 'Returned' to note if the book has been returned or not.

Ok, now i have to display the row in yellow(or light pink) if today's date is just 3 days or less away from 'Due Date', make it red if today's date is 'Due Date' or crossed. All other rows in green.
To do this on client side, CEWP had to be added to the page as the last WebPart.
The script to check for the date and change the row color was

<script type="text/javascript">
// Change these variables to suit your needs
var green = 3; // Items this many days out will be green
var yellow = 1; // Items that are this many days or more are yellow

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++) {
if ((col[c] == 'Due Date') && (rows[r].childNodes[c+1].innerText == 'No')) {
colorIt(rows[r],rows[r].childNodes[c],green,yellow);
}
}
}
}
}

function colorIt(row,x,green,yellow) {
var strDate = x.innerText || x.textContent;
var dt1 = parseInt(strDate.substring(0,2),10);
var mon1 = parseInt(strDate.substring(3,5),10);
var yr1 = parseInt(strDate.substring(6,10),10);
mon1 = mon1 - 1;

var startDate = new Date(yr1, mon1, dt1);
var today = new Date();
var toDate = new Date(today.getFullYear(), today.getMonth() , today.getDate());
var dateDiff = (startDate - toDate )/86400000;;

if (dateDiff > green) {
row.style.backgroundColor='#66FF99';
} else if (dateDiff >= yellow) {
row.style.backgroundColor='Pink';
}
else
{
row.style.backgroundColor='#CC0066';
}
}
</script>

No comments: