How To Highlight Dates Using jQuery UI DatePicker

The jQuery UI datepicker is used a lot across the web, primarily for… well picking dates. It provides the user with a small date display when they click inside an input field, the user can then select a date which is populated into the input field. This date can then be submitted to the server side and used for whatever purpose it is intended.

There is a few great things about the DatePicker which don’t get used as much as it’s basic functionality. The one I am going to look at is the beforeShowDay option. This option allows you to alter the day before it is shown in the calendar popup. Using this option we can mark dates which are important on the datepicker, like up coming events or available dates for a booking system.

The availableDates Variable & available function

The beforeShowDay option takes an array in the format of true/false,”tooltip”. I like to use a separate function to return the array.

    var availableDates = ['26-9-2014','26-11-2014','6-12-2014'];

    function availableFunction(date) {
        availday = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear();
        if (jQuery.inArray(availday, availableDates) > -1) {
            return [true,"eventday",""];
        } else {
            return [true,"other",""];
        }
    }

The function above will run through the availableDates variable and check if the current date on the datepicker is in the variable, if it is then it will be given the class of eventday or a class of other. We can then use this eventday to colour the dates for whatever you like. If you wish to make the dates not selectable then you can also change the true in the second return to false, which will make any date not in the availableDates variable unselectable.

The jQuery UI Datepicker beforeShowDay Option

Now that we have a nice function to return an array based on data we check against, we can now look at how to use that function in the datepicker. To use the function we simply set to the beforeShowDay option. Like so:

    jQuery("#eventpicker").datepicker({
        beforeShowDay: availableFunction
    });

This will now give the dates, 26-9-2014, 26-11-2014 and 6-12-2015 a class of eventday, which you can use in CSS to colour them a different colour. This is great for event systems, if you wish to use them for a booking system then make sure you set the last return in the availableFunction to false instead of true.

I hope this helps you guys and if you need a hand then please leave your comments below, I always try and reply when possible. Good luck with your websites.

Comments