SharePoint – Color List Rows Based on Expiration Date and Add Borders

Add a script editor web part and drop this in it!

<script type="text/javascript">
SP.SOD.executeFunc("clienttemplates.js", "SPClientTemplates", function() { 
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides({
        OnPostRender: function (ctx) {
            // get today's date
            var today = new Date();
			var colorRed = new Date();
			colorRed.setDate(today.getDate() + 180);			
			var colorYellow = new Date();
			colorYellow.setDate(today.getDate() + 365);			
			var colorGreen = new Date();
			colorGreen.setDate(today.getDate() + 365);			
            // zero out the time portion so we will only compare days
            today.setHours(0,0,0,0);
            colorRed.setHours(0,0,0,0);
            colorYellow.setHours(0,0,0,0);
            colorGreen.setHours(0,0,0,0);
			
            var rows = ctx.ListData.Row;
            for (var i = 0; i < rows.length; i++) {
                // get the date set in your date YourDateField
                var itemDate = new Date(rows[i]['Expiration_x0020_Date']);
				//alert(itemDate);
                // zero out the time portion so we only compare days
                itemDate.setHours(0,0,0,0);
                var rowId = GenerateIIDForListItem(ctx, rows[i]);
                var row = document.getElementById(rowId);
                if (row!=null&&itemDate > colorGreen) {                  
                    row.style.backgroundColor = '#77DD77';                  
                }
                if (row!=null&&itemDate <= colorYellow) {                  
                    row.style.backgroundColor = '#FDFD96';                  
                }
                if (row!=null&&itemDate <= colorRed) {                  
                    row.style.backgroundColor = '#FF0000';                  
                }
            }
        }
    });
});
</script>
<style>
    /* Set border for every row */
    .ms-cellstyle {
        border: 1px solid #555555 !important; /* !important needed over override SharePoint inline style */
    }
    .ms-cellStyleNonEditable {
        border: 1px solid #555555 !important; /* !important needed over override SharePoint inline style */
    }
</style>

Leave a Reply

Your email address will not be published. Required fields are marked *