This blog is moved to
http://amalhashim.wordpress.com

Monday, January 24, 2011

Color Coding SharePoint List – With or Without Grouping

Using jQuery we can easily color code lists in SharePoint 2007.

Try using the following script

<script type="text/javascript" src="/_layouts/jquery-1.4.4/jquery-1.4.4.min.js"></script>

<style type="text/css">
.MyStyle
{
font-size: 11px;
background-color: red;
}
</style>
<script type="text/javascript">

$(document).ready(function(){

$(".ms-vb2:contains('Completed')").each(function(){
$(this).addClass(MyStyle);
});
});

</script>


Problem with this approach is, it won’t work in views with grouping. The problem is, on grouping, collapsed group data is not rendered on page load. To tackle this we need to tweak scripts in INIT.js, but directly modifying is not a good practice. To overcome this we can override the method which is rendering the data as shown in the below script block.



<style type="text/css">
.MyStyle
{
font-size: 11px;
background-color: red;
}
</style>

<script type="text/javascript" src="/_layouts/jquery-1.4.4/jquery-1.4.4.min.js"></script>

<script type="text/javascript">

//wait until all of the SharePoint stuff is loaded...
_spBodyOnLoadFunctionNames.push("CustomExpGroupByFix");

function CustomExpGroupByFix()
{
//Replace the function in INIT.JS with our custom function
window.ExpGroupReceiveData=function(x,y){ExpGroupReceiveDataC(x,y)}

}

//This is the exact replica of INIT.JS "ExpGroupReceiveData", we have added color coding code at the end
function ExpGroupReceiveDataC(htmlToRender, groupName)
{
var ctxId="ctx"+groupName.substring(0, groupName.indexOf("-"));
var indexBeginCTXName=htmlToRender.indexOf("CTXName=\"");
if (indexBeginCTXName !=-1)
{
if (ctxId !="ctx1")
{
htmlToRender=htmlToRender.replace(/ CTXName=\"ctx1\" /g, " CTXName=\""+ctxId+"\" ");
}
}
var needOuterWrap=false;
if (htmlToRender.length < 4)
{
needOuterWrap=true;
}
else if (htmlToRender.substring(0,3) !="<tr")
{
needOuterWrap=true;
}
if (needOuterWrap)
{
htmlToRender="<TR><TD>"+htmlToRender+"</TD></TR>";
}
ExpGroupRenderData(htmlToRender, groupName, "true");
g_ExpGroupInProgress=false;
if (g_ExpGroupQueue.length > 0)
{
ExpGroupFetchData(g_ExpGroupQueue.shift());
}

//Color coding the cells
$(".ms-vb2:contains('Completed')").each(function(){
$(this).addClass(MyStyle);
});
}
</script>


To use this script, edit the page –> add a content editor webpart.