blog.scoreman.net

Archive for September, 2014

Week numbers in calendar view – revisited for SharePoint Online

Tuesday, September 9th, 2014

A long time ago I wrote some posts on how you could add week numbers to the monthly calendar view both in SharePoint 2007 and in SharePoint 2010. The solution in SP2007 depended on overriding the calendar’s control template using server side code. Since full trust code is no option in SharePoint Online that does not work. The solution in SP2010 used client side JavaScript but since the calendar view is totally rewritten in SP2013 the SP2010 solution does not work either. So I thought that I would revisit this topic once again for a Office 365/SharePoint Online/SharePoint 2013 version.

The code basically has two main parts. First we need to intercept the client side calls that the calendar view does in SharePoint 2013. Thanks to this post for showing how to do that.

Contoso.WeekNumber.InterceptCalendarEvent = function () {
    ExecuteOrDelayUntilScriptLoaded(function () {
        var onItemsSucceed = SP.UI.ApplicationPages.CalendarStateHandler.prototype.onItemsSucceed;
        SP.UI.ApplicationPages.CalendarStateHandler.prototype.onItemsSucceed = function ($p0, $p1) {
            onItemsSucceed.call(this, $p0, $p1);
            Contoso.WeekNumber.AddWeekNumbers();
        };
    }, "SP.UI.ApplicationPages.Calendar.js");
}

Secondly using JQuery we can find all TH elements and add week numbers.

Contoso.WeekNumber.AddWeekNumbers = function () {
    $(".ms-acal-month > TBODY > TR > TH[evtid='week']").each(function () {
        var firstDay = new Date($(this).attr("date"));
        if (firstDay.toString() != "NaN" && firstDay.toString() != "Invalid Date") {
            var week = firstDay.getWeek(firstDay.getDay());
            week = (week.toString().length == 1) ? '0' + week.toString() : week.toString();
            $(this).html("<div class='ms-picker-weekbox'><acronym title='Week number " + week + "'>" + week + "</acronym></div>");
            $(this).attr("class", "ms-picker-week");
            $(this).css("vertical-align", "middle");
        }
    });
}

For calculating week numbers I used the same JavaScript function that I used in the post on how to add week numbers in SharePoint 2010. It calculates week numbers based on the Gregorian calendar but you can replace that function with whatever you want.

I’ve attached a working solution that is ready to deploy to Office 365. Run the solution from Visual Studio, trust the app and then click on the init button. If all goes well JQuery and a custom javascript file will be added to the site assets library. Also custom actions will be added to the host web so that the scripts are included during page load. This example also works with minimum download strategy (MDS) turned on. The end result looks like this: