AspNet Calendar Extender - highlighting weekends.

10th October 2012

Overview of the problem.

The calendar extender doesn’t visually distinguish between weekdays and weekends.

Searching online for an answer on how to do this, there isn’t much out there. Given the need, I knocked up my own solution which is easily extendable for any particular days by using JavaScript arrays.

The advantage of this solution over others is that:

  • it’s all client-side rather than editing the ajax control toolkit codebase
  • it continues to function after the user has switched month/year

It simply replaces a calendar extender’s in-built function for returning the CSS class of a given date with it’s own version, which is weekend-aware.

Code to fix it.

Add a CSS class definition to your site along the lines of:

.ajax__calendar_weekend { background: #ddd; }

In your master page (or on a specific page instance where the extender is to be used) add the following JavaScript to the top:

function highlightWeekends(sender, args) {
    sender._getCssClass = _getCssClass;
}

function _getCssClass(date, part) {
    if (this._mode !    = 'days') return '';
    var weekday = date.getDay();
    if (weekday == 0 || weekday == 6) {
        return 'ajax__calendar_weekend';
    }

    if (this._isSelected(date, part)) {
        return 'ajax__calendar_active';
    }
    else if (this._isOther(date, part)) {
        return 'ajax__calendar_other';
    }
    else if (this._isTodaysDate(date, part)) {
        return 'ajax__calendar_today';
    } else {
        return '';
    }
}

Markup to enable it.

In your markup for your control add an OnClientShowing event handler (note Showing not Shown, which occurs too late in the lifecycle):

<asp:CalendarExtender ID="CalendarExtender1" PopupButtonID="imgDue" TargetControlID="txtDue" runat="server" OnClientShowing="highlightWeekends" />

Now when the extender is shown the GetCSS Class method is switched and your own code can jump in.

About the performance.

I am aware that by doing this using the OnClientShowing handler, we are actually replacing it every time the calendar is popped up (which is overkill) but the overhead is negligible and I prefer this to insisting pages implement a page loaded handler as unless you are doing so anyway that’s just extra hassle.