jQuery Datepicker: How to Mark the Holidays on Calendar

Jquery UI has a fully-featured and highly customizable date picker control that let us create and customize the control based on our requirements.

To create a basic date control, you just need to call the below single line of code

   $(#date).datepicker();

input field:

  <input type="text" id="date" />

The Date Picker will appears when textbox has the focus, and user can select the date. It disappears when loses focus or date selected. This component is fully localizable, can display multiple months at once, handles any date format, has date range restriction, and more. It has lot options and events available you to tweak.

Here, i would like to create a date control that will mark the holidays on the calendar.
See live Demo here and view the source if you’d like.

Mark Holidays in Date Picker

First, we need to create the holiday array list:

var holiDays =[[2011,01,01,'New Years Day'],[2010,01,14,'Pongal'],[2011,12,25,'Christmas Day']];

If you need to populate the holidays from database, create the array at server side and inject that into client side.

$(function() {
  $("#date").datepicker({ 
     beforeShowDay: setHoliDays
  });

  // set holidays function which is configured in beforeShowDay
 function setHoliDays(date) {
   for (i = 0; i < holiDays.length; i++) {
     if (date.getFullYear() == holiDays[i][0]
    	  && date.getMonth() == holiDays[i][1] - 1
          && date.getDate() == holiDays[i][2]) {
        return [true, 'holiday', holiDays[i][3]];
     }
   }
  return [true, ''];
}

});

Above code, i have used “beforeShowDay” event, it takes a date as a parameter and must return an array with [0] equal to true/false indicating whether or not this date is selectable, [1] equal to a CSS class name(s) or ” for the default presentation, and [2] an optional popup tooltip for this date. It is called for each day in the datepicker before it is displayed.

Here, “setHoliDays” function returns the array with 3 values, [0] as ‘true’ (you can change this to ‘false’ if you want to disable holiday date), [1] is css class name as “holiday” (style the holiday using this css selector), and [1] is name of the holiday to be showed as a tooltip (it will show when you hover on the date)

You have to include the below style inside the head tag to display the holidays with different background color

 <style type="text/css">
  .ui-datepicker td.holiday a, .ui-datepicker td.holiday a:hover {
     background: none #FFEBAF;
     border: 1px solid #BF5A0C;
   }
 </style>
 
12 Comments

Add a Comment

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