Customized datepicker

    I am a big fan of jQuery, but even I have to admit the wretchedness of jQueryUI compared to, for example, YUI. What is only the inability to remove [x] (close button) by standard means in the Dialog widget. But YUI was also written not in a day, and before it became like we see it now, a lot of hacks were written to it, so I think that there is nothing wrong with downloading JUI without getting into its code.

    I already described how to remove [x] in my blog, and now I want to talk about the Calendar widget or what it is called in JUI - Datepicker. The idea of ​​adapting it to the WP calendar is not new, but the bad luck on Datepicker is that you cannot mark dates. That is, it is generally impossible to allocate a day except for the current and weekends. This is a big minus, and now I will show you how to turn this minus into a plus.

    All you need to do is snoop on two calendar methods - the constructor and the table generator.
    1. (function($) {
    2.  
    3.     /**
    4.      * autor: CTAPbIu_MABP
    5.      * email: ctapbiumabp@gmail.com
    6.      * site: mabp.kiev.ua/2009/08/11/customized-datepicker
    7.      * license: MIT & GPL
    8.      * last update: 11.08.2009
    9.      * version: 1.0
    10.      */
    11.     
    12.     // сохраняем старые функции
    13.     var old_datepicker = $.fn.datepicker;
    14.     var old_generateHTML = $.datepicker._generateHTML;
    15.  
    16.     // и делигируем их новым
    17.     $.datepicker._generateHTML = function(inst) {
    18.         // получаем календарь ввиде raw-html
    19.         var _generateHTML = old_generateHTML.apply(this, arguments),
    20.         // выгребаем даты для этого календаря
    21.         dates = inst.settings.hightlight.values;
    22.         titles = inst.settings.hightlight.titles;
    23.         
    24.         // и начинаем расскрашивать
    25.         for (var i in dates){
    26.             if (dates[i].getFullYear() == inst.drawYear && dates[i].getMonth() == inst.drawMonth){
    27.                 _generateHTML = _generateHTML.replace(
    28.                 // магия регулярок
    29.                 new RegExp('' + dates[i].getDate() + '','i'),
    30.                 function(link, classes){
    31.                     // еще больше магии
    32.                     return link.replace(classes, classes + ' ui-state-custom' +
    33.                         (titles[i] ? '" title="'+ titles[i] : ''));
    34.                 });
    35.             }
    36.         }
    37.         return _generateHTML;
    38.     };
    39.     
    40.     // делегируем конструктор
    41.     $.fn.datepicker = function(options){
    42.         // новые опции преобразовываем к объекту
    43.         options.hightlight = $.extend(
    44.             {format:$.datepicker._defaults.dateFormat, values:[], titles:[], settings:{}},
    45.             options.hightlight
    46.         );
    47.         
    48.         // сразу превращаем даты в объекты типа Date для того чтобы сохранить
    49.         options.hightlight.values = $.map(options.hightlight.values, function(value){
    50.             return $.datepicker.parseDate(options.hightlight.format, value, options.hightlight.settings);
    51.         });
    52.         
    53.         return old_datepicker.apply(this, [options]);
    54.     };
    55. })(jQuery);
    * This source code was highlighted with Source Code Highlighter.


    We don’t bother with the code there, but consider an example of use.

    Add a new class in CSS. And create a date picker with new parameters.
    .ui-state-custom {
    border: 1px solid #f0f !important;
    }



    1. $("div#datepicker").datepicker({ // inline datepicker
    2.     firstDay: 1 , // первый день понедельник
    3.     hightlight : { // подсвечиваем
    4.         format:"dd/mm/yy", // формат в котором указаны даты, понимает все форматы которые понимает datepicker, по умолчанию равен $.datepicker._defaults.dateFormat или mm/dd/yy
    5.         values:["1/08/2009","5/08/2009","15/08/2009"], // список дат в том формате который мы тока что указали в прошлом параметре
    6.         titles:["Рас","Два","Три"], // если хотите можно указать список всплывающих подсказок для дат
    7.         settings:{} // дополнительные параметры для функции преобразования строк в дату можно посмотреть в комментариях к коду датапикера
    8.     }
    9. });
    * This source code was highlighted with Source Code Highlighter.

    In action, you can look at my blog

    Also popular now: