Advertisement
Guest User

bootstrap.datepicker.js

a guest
Sep 1st, 2017
273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*! =========================================================
  2.  * bootstrap-datepicker.js
  3.  * Original Idea: http://www.eyecon.ro/bootstrap-datepicker (Copyright 2012 Stefan Petre)
  4.  * Updated by AymKdn (http://kodono.info - https://github.com/Aymkdn/Datepicker-for-Bootstrap)
  5.  * =========================================================
  6.  *
  7.  * Licensed under the Apache License, Version 2.0 (the "License");
  8.  * you may not use this file except in compliance with the License.
  9.  * You may obtain a copy of the License at
  10.  *
  11.  * http://www.apache.org/licenses/LICENSE-2.0
  12.  *
  13.  * Unless required by applicable law or agreed to in writing, software
  14.  * distributed under the License is distributed on an "AS IS" BASIS,
  15.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16.  * See the License for the specific language governing permissions and
  17.  * limitations under the License.
  18.  * ========================================================= */
  19.  
  20. !function( $ ) {
  21.    
  22.     // Picker object
  23.    
  24.     var Datepicker = function(element, options){
  25.         this.element = $(element);
  26.         this.format = DPGlobal.parseFormat(options.format||this.element.data('date-format')||'mm/dd/yyyy');
  27.         this.picker = $(DPGlobal.template).appendTo('body').hide().on('mousedown.Datepicker',$.proxy(this.mousedown, this)).on('click.Datepicker',$.proxy(this.click, this));
  28.  
  29.         this.isInput = this.element.is('input') || this.element.is('textarea');
  30.         this.component = this.element.is('.date') ? this.element.find('.add-on') : false;
  31.        
  32.         if (this.isInput) {
  33.             this.element.on({
  34.                 "focus.Datepicker": $.proxy(this.show, this),
  35.                 "click.Datepicker": $.proxy(this.show, this),
  36.                 "blur.Datepicker": $.proxy(this.blur, this),
  37.                 "keyup.Datepicker": $.proxy(this.update, this),
  38.                 "keydown.Datepicker": $.proxy(this.keydown, this)
  39.             });
  40.         } else {
  41.             if (this.component){
  42.                 this.component.on('click.Datepicker', $.proxy(this.show, this));
  43.             } else {
  44.                 this.element.on('click.Datepicker', $.proxy(this.show, this));
  45.             }
  46.         }
  47.        
  48.         this.viewMode = 0;
  49.         this.weekStart = options.weekStart||this.element.data('date-weekstart')||0;
  50.         this.scroll = (options.scroll != undefined ? options.scroll : true);
  51.         this.weekEnd = this.weekStart == 0 ? 6 : this.weekStart - 1;
  52.         this.fillDow();
  53.         this.fillMonths();
  54.         this.update();
  55.         this.showMode();
  56.     };
  57.    
  58.     Datepicker.prototype = {
  59.         constructor: Datepicker,
  60.        
  61.         show: function(e) {
  62.           $('div.datepicker.dropdown-menu').hide(); //make sure to hide all other calendars
  63.             this.picker.show();
  64.             this.height = this.component ? this.component.outerHeight() : this.element.outerHeight();
  65.             this.place();
  66.             $(window).on('resize.Datepicker', $.proxy(this.place, this));
  67.             $('body').on('click.Datepicker', $.proxy(this.hide, this));
  68.             if (e) {
  69.                 e.stopPropagation();
  70.                 e.preventDefault();
  71.             }
  72.             if (!this.isInput) {
  73.                 $(document).on('mousedown.Datepicker', $.proxy(this.hide, this));
  74.             }
  75.             this.element.trigger({
  76.                 type: 'show',
  77.                 date: this.date
  78.             });
  79.             // make sure we see the datepicker
  80.             var elem = this.picker;
  81.             var docScrollTop = $(document).scrollTop();
  82.             var winHeight = $(window).height();
  83.             var elemTop = elem.position().top;
  84.             var elemHeight = elem.height();
  85.             if (this.scroll && docScrollTop+winHeight<elemTop+elemHeight)
  86.                           $(document).scrollTop(elemTop-elemHeight);
  87.         },
  88.        
  89.         setValue: function() {
  90.             var formated = DPGlobal.formatDate(this.date, this.format);
  91.             if (!this.isInput) {
  92.                 if (this.component){
  93.                     this.element.find('input').prop('value', formated);
  94.                 }
  95.                 this.element.data('date', formated);
  96.             } else {
  97.                 this.element.prop('value', formated);
  98.             }
  99.         },
  100.        
  101.         place: function(){
  102.             var offset = this.component ? this.component.offset() : this.element.offset();
  103.             this.picker.css({
  104.                 top: offset.top + this.height,
  105.                 left: offset.left
  106.             });
  107.         },
  108.        
  109.         update: function(){
  110.           var date = this.element.val();
  111.             this.date = DPGlobal.parseDate(
  112.                 date ? date : this.element.data('date'),
  113.                 this.format
  114.             );
  115.             this.viewDate = new Date(this.date);
  116.             this.fill();
  117.         },
  118.        
  119.         fillDow: function(){
  120.             var dowCnt = this.weekStart;
  121.             var html = '<tr>';
  122.             while (dowCnt < this.weekStart + 7) {
  123.                 html += '<th class="dow">'+DPGlobal.dates.daysMin[(dowCnt++)%7]+'</th>';
  124.             }
  125.             html += '</tr>';
  126.             this.picker.find('.datepicker-days thead').append(html);
  127.         },
  128.        
  129.         fillMonths: function(){
  130.             var html = '';
  131.             var i = 0
  132.             while (i < 12) {
  133.                 html += '<span class="month">'+DPGlobal.dates.monthsShort[i++]+'</span>';
  134.             }
  135.             this.picker.find('.datepicker-months td').append(html);
  136.         },
  137.        
  138.         fill: function() {
  139.             var d = new Date(this.viewDate),
  140.                 year = d.getFullYear(),
  141.                 month = d.getMonth(),
  142.                 currentDate = this.date.valueOf();
  143.             this.picker.find('.datepicker-days th:eq(1)')
  144.                         .text(DPGlobal.dates.months[month]+' '+year);
  145.             var prevMonth = new Date(year, month-1, 28,0,0,0,0),
  146.                 day = DPGlobal.getDaysInMonth(prevMonth.getFullYear(), prevMonth.getMonth());
  147.             prevMonth.setDate(day);
  148.             prevMonth.setDate(day - (prevMonth.getDay() - this.weekStart + 7)%7);
  149.             var nextMonth = new Date(prevMonth);
  150.             nextMonth.setDate(nextMonth.getDate() + 42);
  151.             nextMonth = nextMonth.valueOf();
  152.             html = [];
  153.             var clsName;
  154.             while(prevMonth.valueOf() < nextMonth) {
  155.                 if (prevMonth.getDay() == this.weekStart) {
  156.                     html.push('<tr>');
  157.                 }
  158.                 clsName = '';
  159.                 if (prevMonth.getMonth() < month) {
  160.                     clsName += ' old';
  161.                 } else if (prevMonth.getMonth() > month) {
  162.                     clsName += ' new';
  163.                 }
  164.                 if (prevMonth.valueOf() == currentDate) {
  165.                     clsName += ' active';
  166.                 }
  167.                 html.push('<td class="day'+clsName+'">'+prevMonth.getDate() + '</td>');
  168.                 if (prevMonth.getDay() == this.weekEnd) {
  169.                     html.push('</tr>');
  170.                 }
  171.                 prevMonth.setDate(prevMonth.getDate()+1);
  172.             }
  173.             this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
  174.             var currentYear = this.date.getFullYear();
  175.            
  176.             var months = this.picker.find('.datepicker-months')
  177.                         .find('th:eq(1)')
  178.                             .text(year)
  179.                             .end()
  180.                         .find('span').removeClass('active');
  181.             if (currentYear == year) {
  182.                 months.eq(this.date.getMonth()).addClass('active');
  183.             }
  184.            
  185.             html = '';
  186.             year = parseInt(year/10, 10) * 10;
  187.             var yearCont = this.picker.find('.datepicker-years')
  188.                                 .find('th:eq(1)')
  189.                                     .text(year + '-' + (year + 9))
  190.                                     .end()
  191.                                 .find('td');
  192.             year -= 1;
  193.             for (var i = -1; i < 11; i++) {
  194.                 html += '<span class="year'+(i == -1 || i == 10 ? ' old' : '')+(currentYear == year ? ' active' : '')+'">'+year+'</span>';
  195.                 year += 1;
  196.             }
  197.             yearCont.html(html);
  198.         },
  199.        
  200.         blur:function(e) {
  201.     },
  202.        
  203.         hide: function(e){
  204.         this.picker.hide();
  205.             $(window).off('resize.Datepicker', this.place);
  206.             this.viewMode = 0;
  207.             this.showMode();
  208.             if (!this.isInput) {
  209.                 $(document).off('mousedown.Datepicker', this.hide);
  210.             }
  211.             $('body').off('click.Datepicker',$.proxy(this.click, this));
  212.         },
  213.         click:function(e) {
  214.             e.stopPropagation();
  215.             e.preventDefault();
  216.         },
  217.         mousedown: function(e) {
  218.             e.stopPropagation();
  219.             e.preventDefault();
  220.             var target = $(e.target).closest('span, td, th');
  221.             if (target.length == 1) {
  222.                 switch(target[0].nodeName.toLowerCase()) {
  223.                     case 'th':
  224.                         switch(target[0].className) {
  225.                             case 'switch':
  226.                                 this.showMode(1);
  227.                                 break;
  228.                             case 'prev':
  229.                             case 'next':
  230.                                 this.viewDate['set'+DPGlobal.modes[this.viewMode].navFnc].call(
  231.                                     this.viewDate,
  232.                                     this.viewDate['get'+DPGlobal.modes[this.viewMode].navFnc].call(this.viewDate) +
  233.                                     DPGlobal.modes[this.viewMode].navStep * (target[0].className == 'prev' ? -1 : 1)
  234.                                 );
  235.                                 this.fill();
  236.                                 break;
  237.                         }
  238.                         break;
  239.                     case 'span':
  240.                         if (target.is('.month')) {
  241.                             var month = target.parent().find('span').index(target);
  242.                             this.viewDate.setMonth(month);
  243.                         } else {
  244.                             var year = parseInt(target.text(), 10)||0;
  245.                             this.viewDate.setFullYear(year);
  246.                         }
  247.                         this.showMode(-1);
  248.                         this.fill();
  249.                         break;
  250.                     case 'td':
  251.                         if (target.is('.day')){
  252.                             var day = parseInt(target.text(), 10)||1;
  253.                             var month = this.viewDate.getMonth();
  254.                             if (target.is('.old')) {
  255.                                 month -= 1;
  256.                             } else if (target.is('.new')) {
  257.                                 month += 1;
  258.                             }
  259.                             var year = this.viewDate.getFullYear();
  260.                             this.date = new Date(year, month, day,0,0,0,0);
  261.                             this.viewDate = new Date(year, month, day,0,0,0,0);
  262.                             this.fill();
  263.                             this.setValue();
  264.                             this.element.trigger({
  265.                                 type: 'changeDate',
  266.                                 date: this.date
  267.                             });
  268.                             this.hide();
  269.                         }
  270.                         break;
  271.                 }
  272.             }
  273.         },
  274.         keydown:function(e) {
  275.                   var keyCode = e.keyCode || e.which;
  276.                   if (keyCode == 9) this.hide(); // when hiting TAB, for accessibility
  277.                 },
  278.    
  279.         showMode: function(dir) {
  280.             if (dir) {
  281.                 this.viewMode = Math.max(0, Math.min(2, this.viewMode + dir));
  282.             }
  283.             this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();
  284.         },
  285.        
  286.         destroy: function() { this.element.removeData("datepicker").off(".Datepicker"); this.picker.remove() }
  287.     };
  288.    
  289.     $.fn.datepicker = function ( option ) {
  290.         return this.each(function () {
  291.             var $this = $(this),
  292.                 data = $this.data('datepicker'),
  293.                 options = typeof option == 'object' && option;
  294.             if (!data) {
  295.                 $this.data('datepicker', (data = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options))));
  296.             }
  297.             if (typeof option == 'string') data[option]();
  298.         });
  299.     };
  300.  
  301.     $.fn.datepicker.defaults = {
  302.     };
  303.     $.fn.datepicker.Constructor = Datepicker;
  304.    
  305.     var DPGlobal = {
  306.         modes: [
  307.             {
  308.                 clsName: 'days',
  309.                 navFnc: 'Month',
  310.                 navStep: 1
  311.             },
  312.             {
  313.                 clsName: 'months',
  314.                 navFnc: 'FullYear',
  315.                 navStep: 1
  316.             },
  317.             {
  318.                 clsName: 'years',
  319.                 navFnc: 'FullYear',
  320.                 navStep: 10
  321.         }],
  322.         dates:{
  323.             days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
  324.             daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
  325.             daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
  326.             months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
  327.             monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
  328.         },
  329.         isLeapYear: function (year) {
  330.             return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0))
  331.         },
  332.         getDaysInMonth: function (year, month) {
  333.             return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
  334.         },
  335.         parseFormat: function(format){
  336.             var separator = format.match(/[.\/-].*?/),
  337.                 parts = format.split(/\W+/);
  338.             if (!separator || !parts || parts.length == 0){
  339.                 throw new Error("Invalid date format.");
  340.             }
  341.             return {separator: separator, parts: parts};
  342.         },
  343.         parseDate: function(date, format) {
  344.           var today=new Date();
  345.           if (!date) date="";
  346.             var parts = date.split(format.separator),
  347.                 date = new Date(today.getFullYear(),today.getMonth(),today.getDate(),0,0,0),
  348.                 val;
  349.             if (parts.length == format.parts.length) {
  350.                 for (var i=0, cnt = format.parts.length; i < cnt; i++) {
  351.                     val = parseInt(parts[i], 10)||1;
  352.                     switch(format.parts[i]) {
  353.                         case 'dd':
  354.                         case 'd':
  355.                             date.setDate(val);
  356.                             break;
  357.                         case 'mm':
  358.                         case 'm':
  359.                             date.setMonth(val - 1);
  360.                             break;
  361.                         case 'yy':
  362.                             date.setFullYear(2000 + val);
  363.                             break;
  364.                         case 'yyyy':
  365.                             date.setFullYear(val);
  366.                             break;
  367.                     }
  368.                 }
  369.             }
  370.             return date;
  371.         },
  372.         formatDate: function(date, format){
  373.             var val = {
  374.                 d: date.getDate(),
  375.                 m: date.getMonth() + 1,
  376.                 yy: date.getFullYear().toString().substring(2),
  377.                 yyyy: date.getFullYear()
  378.             };
  379.             val.dd = (val.d < 10 ? '0' : '') + val.d;
  380.             val.mm = (val.m < 10 ? '0' : '') + val.m;
  381.             var date = [];
  382.             for (var i=0, cnt = format.parts.length; i < cnt; i++) {
  383.                 date.push(val[format.parts[i]]);
  384.             }
  385.             return date.join(format.separator);
  386.         },
  387.         headTemplate: '<thead>'+
  388.                             '<tr>'+
  389.                                 '<th class="prev"><i class="icon-arrow-left"/></th>'+
  390.                                 '<th colspan="5" class="switch"></th>'+
  391.                                 '<th class="next"><i class="icon-arrow-right"/></th>'+
  392.                             '</tr>'+
  393.                         '</thead>',
  394.         contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>'
  395.     };
  396.     DPGlobal.template = '<div class="datepicker dropdown-menu">'+
  397.                             '<div class="datepicker-days">'+
  398.                                 '<table class=" table-condensed">'+
  399.                                     DPGlobal.headTemplate+
  400.                                     '<tbody></tbody>'+
  401.                                 '</table>'+
  402.                             '</div>'+
  403.                             '<div class="datepicker-months">'+
  404.                                 '<table class="table-condensed">'+
  405.                                     DPGlobal.headTemplate+
  406.                                     DPGlobal.contTemplate+
  407.                                 '</table>'+
  408.                             '</div>'+
  409.                             '<div class="datepicker-years">'+
  410.                                 '<table class="table-condensed">'+
  411.                                     DPGlobal.headTemplate+
  412.                                     DPGlobal.contTemplate+
  413.                                 '</table>'+
  414.                             '</div>'+
  415.                         '</div>';
  416.  
  417. }( window.jQuery )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement