daterangepicker.js 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632
  1. /**
  2. * @version: 2.1.24
  3. * @author: Dan Grossman http://www.dangrossman.info/
  4. * @copyright: Copyright (c) 2012-2016 Dan Grossman. All rights reserved.
  5. * @license: Licensed under the MIT license. See http://www.opensource.org/licenses/mit-license.php
  6. * @website: https://www.improvely.com/
  7. */
  8. // Follow the UMD template https://github.com/umdjs/umd/blob/master/templates/returnExportsGlobal.js
  9. (function (root, factory) {
  10. if (typeof define === 'function' && define.amd) {
  11. // AMD. Make globaly available as well
  12. define(['moment', 'jquery'], function (moment, jquery) {
  13. return (root.daterangepicker = factory(moment, jquery));
  14. });
  15. } else if (typeof module === 'object' && module.exports) {
  16. // Node / Browserify
  17. //isomorphic issue
  18. var jQuery = (typeof window != 'undefined') ? window.jQuery : undefined;
  19. if (!jQuery) {
  20. jQuery = require('jquery');
  21. if (!jQuery.fn) jQuery.fn = {};
  22. }
  23. module.exports = factory(require('moment'), jQuery);
  24. } else {
  25. // Browser globals
  26. root.daterangepicker = factory(root.moment, root.jQuery);
  27. }
  28. }(this, function(moment, $) {
  29. var DateRangePicker = function(element, options, cb) {
  30. //default settings for options
  31. this.parentEl = 'body';
  32. this.element = $(element);
  33. this.startDate = moment().startOf('day');
  34. this.endDate = moment().endOf('day');
  35. this.minDate = false;
  36. this.maxDate = false;
  37. this.dateLimit = false;
  38. this.autoApply = false;
  39. this.singleDatePicker = false;
  40. this.showDropdowns = false;
  41. this.showWeekNumbers = false;
  42. this.showISOWeekNumbers = false;
  43. this.showCustomRangeLabel = true;
  44. this.timePicker = false;
  45. this.timePicker24Hour = false;
  46. this.timePickerIncrement = 1;
  47. this.timePickerSeconds = false;
  48. this.linkedCalendars = true;
  49. this.autoUpdateInput = true;
  50. this.alwaysShowCalendars = false;
  51. this.ranges = {};
  52. this.opens = 'right';
  53. if (this.element.hasClass('pull-right'))
  54. this.opens = 'left';
  55. this.drops = 'down';
  56. if (this.element.hasClass('dropup'))
  57. this.drops = 'up';
  58. this.buttonClasses = 'btn btn-sm';
  59. this.applyClass = 'btn-success';
  60. this.cancelClass = 'btn-default';
  61. this.locale = {
  62. direction: 'ltr',
  63. format: moment.localeData().longDateFormat('L'),
  64. separator: ' - ',
  65. applyLabel: 'Apply',
  66. cancelLabel: 'Cancel',
  67. weekLabel: 'W',
  68. customRangeLabel: 'Custom Range',
  69. daysOfWeek: moment.weekdaysMin(),
  70. monthNames: moment.monthsShort(),
  71. firstDay: moment.localeData().firstDayOfWeek()
  72. };
  73. this.callback = function() { };
  74. //some state information
  75. this.isShowing = false;
  76. this.leftCalendar = {};
  77. this.rightCalendar = {};
  78. //custom options from user
  79. if (typeof options !== 'object' || options === null)
  80. options = {};
  81. //allow setting options with data attributes
  82. //data-api options will be overwritten with custom javascript options
  83. options = $.extend(this.element.data(), options);
  84. //html template for the picker UI
  85. if (typeof options.template !== 'string' && !(options.template instanceof $))
  86. options.template = '<div class="daterangepicker dropdown-menu">' +
  87. '<div class="calendar left">' +
  88. '<div class="daterangepicker_input">' +
  89. '<input class="input-mini form-control" type="text" name="daterangepicker_start" value="" />' +
  90. '<i class="fa fa-calendar glyphicon glyphicon-calendar"></i>' +
  91. '<div class="calendar-time">' +
  92. '<div></div>' +
  93. '<i class="fa fa-clock-o glyphicon glyphicon-time"></i>' +
  94. '</div>' +
  95. '</div>' +
  96. '<div class="calendar-table"></div>' +
  97. '</div>' +
  98. '<div class="calendar right">' +
  99. '<div class="daterangepicker_input">' +
  100. '<input class="input-mini form-control" type="text" name="daterangepicker_end" value="" />' +
  101. '<i class="fa fa-calendar glyphicon glyphicon-calendar"></i>' +
  102. '<div class="calendar-time">' +
  103. '<div></div>' +
  104. '<i class="fa fa-clock-o glyphicon glyphicon-time"></i>' +
  105. '</div>' +
  106. '</div>' +
  107. '<div class="calendar-table"></div>' +
  108. '</div>' +
  109. '<div class="ranges">' +
  110. '<div class="range_inputs">' +
  111. '<button class="applyBtn" disabled="disabled" type="button"></button> ' +
  112. '<button class="cancelBtn" type="button"></button>' +
  113. '</div>' +
  114. '</div>' +
  115. '</div>';
  116. this.parentEl = (options.parentEl && $(options.parentEl).length) ? $(options.parentEl) : $(this.parentEl);
  117. this.container = $(options.template).appendTo(this.parentEl);
  118. //
  119. // handle all the possible options overriding defaults
  120. //
  121. if (typeof options.locale === 'object') {
  122. if (typeof options.locale.direction === 'string')
  123. this.locale.direction = options.locale.direction;
  124. if (typeof options.locale.format === 'string')
  125. this.locale.format = options.locale.format;
  126. if (typeof options.locale.separator === 'string')
  127. this.locale.separator = options.locale.separator;
  128. if (typeof options.locale.daysOfWeek === 'object')
  129. this.locale.daysOfWeek = options.locale.daysOfWeek.slice();
  130. if (typeof options.locale.monthNames === 'object')
  131. this.locale.monthNames = options.locale.monthNames.slice();
  132. if (typeof options.locale.firstDay === 'number')
  133. this.locale.firstDay = options.locale.firstDay;
  134. if (typeof options.locale.applyLabel === 'string')
  135. this.locale.applyLabel = options.locale.applyLabel;
  136. if (typeof options.locale.cancelLabel === 'string')
  137. this.locale.cancelLabel = options.locale.cancelLabel;
  138. if (typeof options.locale.weekLabel === 'string')
  139. this.locale.weekLabel = options.locale.weekLabel;
  140. if (typeof options.locale.customRangeLabel === 'string')
  141. this.locale.customRangeLabel = options.locale.customRangeLabel;
  142. }
  143. this.container.addClass(this.locale.direction);
  144. if (typeof options.startDate === 'string')
  145. this.startDate = moment(options.startDate, this.locale.format);
  146. if (typeof options.endDate === 'string')
  147. this.endDate = moment(options.endDate, this.locale.format);
  148. if (typeof options.minDate === 'string')
  149. this.minDate = moment(options.minDate, this.locale.format);
  150. if (typeof options.maxDate === 'string')
  151. this.maxDate = moment(options.maxDate, this.locale.format);
  152. if (typeof options.startDate === 'object')
  153. this.startDate = moment(options.startDate);
  154. if (typeof options.endDate === 'object')
  155. this.endDate = moment(options.endDate);
  156. if (typeof options.minDate === 'object')
  157. this.minDate = moment(options.minDate);
  158. if (typeof options.maxDate === 'object')
  159. this.maxDate = moment(options.maxDate);
  160. // sanity check for bad options
  161. if (this.minDate && this.startDate.isBefore(this.minDate))
  162. this.startDate = this.minDate.clone();
  163. // sanity check for bad options
  164. if (this.maxDate && this.endDate.isAfter(this.maxDate))
  165. this.endDate = this.maxDate.clone();
  166. if (typeof options.applyClass === 'string')
  167. this.applyClass = options.applyClass;
  168. if (typeof options.cancelClass === 'string')
  169. this.cancelClass = options.cancelClass;
  170. if (typeof options.dateLimit === 'object')
  171. this.dateLimit = options.dateLimit;
  172. if (typeof options.opens === 'string')
  173. this.opens = options.opens;
  174. if (typeof options.drops === 'string')
  175. this.drops = options.drops;
  176. if (typeof options.showWeekNumbers === 'boolean')
  177. this.showWeekNumbers = options.showWeekNumbers;
  178. if (typeof options.showISOWeekNumbers === 'boolean')
  179. this.showISOWeekNumbers = options.showISOWeekNumbers;
  180. if (typeof options.buttonClasses === 'string')
  181. this.buttonClasses = options.buttonClasses;
  182. if (typeof options.buttonClasses === 'object')
  183. this.buttonClasses = options.buttonClasses.join(' ');
  184. if (typeof options.singleClasses === 'string')
  185. this.singleClasses = options.singleClasses;
  186. if (typeof options.singleClasses === 'object')
  187. this.singleClasses = options.singleClasses.join(' ');
  188. if (typeof options.showDropdowns === 'boolean')
  189. this.showDropdowns = options.showDropdowns;
  190. if (typeof options.showCustomRangeLabel === 'boolean')
  191. this.showCustomRangeLabel = options.showCustomRangeLabel;
  192. if (typeof options.singleDatePicker === 'boolean') {
  193. this.singleDatePicker = options.singleDatePicker;
  194. if (this.singleDatePicker)
  195. this.endDate = this.startDate.clone();
  196. }
  197. if (typeof options.timePicker === 'boolean')
  198. this.timePicker = options.timePicker;
  199. if (typeof options.timePickerSeconds === 'boolean')
  200. this.timePickerSeconds = options.timePickerSeconds;
  201. if (typeof options.timePickerIncrement === 'number')
  202. this.timePickerIncrement = options.timePickerIncrement;
  203. if (typeof options.timePicker24Hour === 'boolean')
  204. this.timePicker24Hour = options.timePicker24Hour;
  205. if (typeof options.autoApply === 'boolean')
  206. this.autoApply = options.autoApply;
  207. if (typeof options.autoUpdateInput === 'boolean')
  208. this.autoUpdateInput = options.autoUpdateInput;
  209. if (typeof options.linkedCalendars === 'boolean')
  210. this.linkedCalendars = options.linkedCalendars;
  211. if (typeof options.isInvalidDate === 'function')
  212. this.isInvalidDate = options.isInvalidDate;
  213. if (typeof options.isCustomDate === 'function')
  214. this.isCustomDate = options.isCustomDate;
  215. if (typeof options.alwaysShowCalendars === 'boolean')
  216. this.alwaysShowCalendars = options.alwaysShowCalendars;
  217. // update day names order to firstDay
  218. if (this.locale.firstDay != 0) {
  219. var iterator = this.locale.firstDay;
  220. while (iterator > 0) {
  221. this.locale.daysOfWeek.push(this.locale.daysOfWeek.shift());
  222. iterator--;
  223. }
  224. }
  225. var start, end, range;
  226. //if no start/end dates set, check if an input element contains initial values
  227. if (typeof options.startDate === 'undefined' && typeof options.endDate === 'undefined') {
  228. if ($(this.element).is('input[type=text]')) {
  229. var val = $(this.element).val(),
  230. split = val.split(this.locale.separator);
  231. start = end = null;
  232. if (split.length == 2) {
  233. start = moment(split[0], this.locale.format);
  234. end = moment(split[1], this.locale.format);
  235. } else if (this.singleDatePicker && val !== "") {
  236. start = moment(val, this.locale.format);
  237. end = moment(val, this.locale.format);
  238. }
  239. if (start !== null && end !== null) {
  240. this.setStartDate(start);
  241. this.setEndDate(end);
  242. }
  243. }
  244. }
  245. if (typeof options.ranges === 'object') {
  246. for (range in options.ranges) {
  247. if (typeof options.ranges[range][0] === 'string')
  248. start = moment(options.ranges[range][0], this.locale.format);
  249. else
  250. start = moment(options.ranges[range][0]);
  251. if (typeof options.ranges[range][1] === 'string')
  252. end = moment(options.ranges[range][1], this.locale.format);
  253. else
  254. end = moment(options.ranges[range][1]);
  255. // If the start or end date exceed those allowed by the minDate or dateLimit
  256. // options, shorten the range to the allowable period.
  257. if (this.minDate && start.isBefore(this.minDate))
  258. start = this.minDate.clone();
  259. var maxDate = this.maxDate;
  260. if (this.dateLimit && maxDate && start.clone().add(this.dateLimit).isAfter(maxDate))
  261. maxDate = start.clone().add(this.dateLimit);
  262. if (maxDate && end.isAfter(maxDate))
  263. end = maxDate.clone();
  264. // If the end of the range is before the minimum or the start of the range is
  265. // after the maximum, don't display this range option at all.
  266. if ((this.minDate && end.isBefore(this.minDate, this.timepicker ? 'minute' : 'day'))
  267. || (maxDate && start.isAfter(maxDate, this.timepicker ? 'minute' : 'day')))
  268. continue;
  269. //Support unicode chars in the range names.
  270. var elem = document.createElement('textarea');
  271. elem.innerHTML = range;
  272. var rangeHtml = elem.value;
  273. this.ranges[rangeHtml] = [start, end];
  274. }
  275. var list = '<ul>';
  276. for (range in this.ranges) {
  277. list += '<li data-range-key="' + range + '">' + range + '</li>';
  278. }
  279. if (this.showCustomRangeLabel) {
  280. list += '<li data-range-key="' + this.locale.customRangeLabel + '">' + this.locale.customRangeLabel + '</li>';
  281. }
  282. list += '</ul>';
  283. this.container.find('.ranges').prepend(list);
  284. }
  285. if (typeof cb === 'function') {
  286. this.callback = cb;
  287. }
  288. if (!this.timePicker) {
  289. this.startDate = this.startDate.startOf('day');
  290. this.endDate = this.endDate.endOf('day');
  291. this.container.find('.calendar-time').hide();
  292. }
  293. //can't be used together for now
  294. if (this.timePicker && this.autoApply)
  295. this.autoApply = false;
  296. if (this.autoApply && typeof options.ranges !== 'object') {
  297. this.container.find('.ranges').hide();
  298. } else if (this.autoApply) {
  299. this.container.find('.applyBtn, .cancelBtn').addClass('hide');
  300. }
  301. if (this.singleDatePicker) {
  302. this.container.addClass('single');
  303. if (this.singleClasses) {
  304. this.container.addClass(this.singleClasses);
  305. }
  306. this.container.find('.calendar.left').addClass('single');
  307. this.container.find('.calendar.left').show();
  308. this.container.find('.calendar.right').hide();
  309. this.container.find('.daterangepicker_input input, .daterangepicker_input > i').hide();
  310. if (this.timePicker) {
  311. this.container.find('.ranges ul').hide();
  312. } else {
  313. this.container.find('.ranges').hide();
  314. }
  315. }
  316. if ((typeof options.ranges === 'undefined' && !this.singleDatePicker) || this.alwaysShowCalendars) {
  317. this.container.addClass('show-calendar');
  318. }
  319. this.container.addClass('opens' + this.opens);
  320. //swap the position of the predefined ranges if opens right
  321. if (typeof options.ranges !== 'undefined' && this.opens == 'right') {
  322. this.container.find('.ranges').prependTo( this.container.find('.calendar.left').parent() );
  323. }
  324. //apply CSS classes and labels to buttons
  325. this.container.find('.applyBtn, .cancelBtn').addClass(this.buttonClasses);
  326. if (this.applyClass.length)
  327. this.container.find('.applyBtn').addClass(this.applyClass);
  328. if (this.cancelClass.length)
  329. this.container.find('.cancelBtn').addClass(this.cancelClass);
  330. this.container.find('.applyBtn').html(this.locale.applyLabel);
  331. this.container.find('.cancelBtn').html(this.locale.cancelLabel);
  332. //
  333. // event listeners
  334. //
  335. this.container.find('.calendar')
  336. .on('click.daterangepicker', '.prev', $.proxy(this.clickPrev, this))
  337. .on('click.daterangepicker', '.next', $.proxy(this.clickNext, this))
  338. .on('mousedown.daterangepicker', 'td.available', $.proxy(this.clickDate, this))
  339. .on('mouseenter.daterangepicker', 'td.available', $.proxy(this.hoverDate, this))
  340. .on('mouseleave.daterangepicker', 'td.available', $.proxy(this.updateFormInputs, this))
  341. .on('change.daterangepicker', 'select.yearselect', $.proxy(this.monthOrYearChanged, this))
  342. .on('change.daterangepicker', 'select.monthselect', $.proxy(this.monthOrYearChanged, this))
  343. .on('change.daterangepicker', 'select.hourselect,select.minuteselect,select.secondselect,select.ampmselect', $.proxy(this.timeChanged, this))
  344. .on('click.daterangepicker', '.daterangepicker_input input', $.proxy(this.showCalendars, this))
  345. .on('focus.daterangepicker', '.daterangepicker_input input', $.proxy(this.formInputsFocused, this))
  346. .on('blur.daterangepicker', '.daterangepicker_input input', $.proxy(this.formInputsBlurred, this))
  347. .on('change.daterangepicker', '.daterangepicker_input input', $.proxy(this.formInputsChanged, this));
  348. this.container.find('.ranges')
  349. .on('click.daterangepicker', 'button.applyBtn', $.proxy(this.clickApply, this))
  350. .on('click.daterangepicker', 'button.cancelBtn', $.proxy(this.clickCancel, this))
  351. .on('click.daterangepicker', 'li', $.proxy(this.clickRange, this))
  352. .on('mouseenter.daterangepicker', 'li', $.proxy(this.hoverRange, this))
  353. .on('mouseleave.daterangepicker', 'li', $.proxy(this.updateFormInputs, this));
  354. if (this.element.is('input') || this.element.is('button')) {
  355. this.element.on({
  356. 'click.daterangepicker': $.proxy(this.show, this),
  357. 'focus.daterangepicker': $.proxy(this.show, this),
  358. 'keyup.daterangepicker': $.proxy(this.elementChanged, this),
  359. 'keydown.daterangepicker': $.proxy(this.keydown, this)
  360. });
  361. } else {
  362. this.element.on('click.daterangepicker', $.proxy(this.toggle, this));
  363. }
  364. //
  365. // if attached to a text input, set the initial value
  366. //
  367. if (this.element.is('input') && !this.singleDatePicker && this.autoUpdateInput) {
  368. this.element.val(this.startDate.format(this.locale.format) + this.locale.separator + this.endDate.format(this.locale.format));
  369. this.element.trigger('change');
  370. } else if (this.element.is('input') && this.autoUpdateInput) {
  371. this.element.val(this.startDate.format(this.locale.format));
  372. this.element.trigger('change');
  373. }
  374. };
  375. DateRangePicker.prototype = {
  376. constructor: DateRangePicker,
  377. setStartDate: function(startDate) {
  378. if (typeof startDate === 'string')
  379. this.startDate = moment(startDate, this.locale.format);
  380. if (typeof startDate === 'object')
  381. this.startDate = moment(startDate);
  382. if (!this.timePicker)
  383. this.startDate = this.startDate.startOf('day');
  384. if (this.timePicker && this.timePickerIncrement)
  385. this.startDate.minute(Math.round(this.startDate.minute() / this.timePickerIncrement) * this.timePickerIncrement);
  386. if (this.minDate && this.startDate.isBefore(this.minDate)) {
  387. this.startDate = this.minDate.clone();
  388. if (this.timePicker && this.timePickerIncrement)
  389. this.startDate.minute(Math.round(this.startDate.minute() / this.timePickerIncrement) * this.timePickerIncrement);
  390. }
  391. if (this.maxDate && this.startDate.isAfter(this.maxDate)) {
  392. this.startDate = this.maxDate.clone();
  393. if (this.timePicker && this.timePickerIncrement)
  394. this.startDate.minute(Math.floor(this.startDate.minute() / this.timePickerIncrement) * this.timePickerIncrement);
  395. }
  396. if (!this.isShowing)
  397. this.updateElement();
  398. this.updateMonthsInView();
  399. },
  400. setEndDate: function(endDate) {
  401. if (typeof endDate === 'string')
  402. this.endDate = moment(endDate, this.locale.format);
  403. if (typeof endDate === 'object')
  404. this.endDate = moment(endDate);
  405. if (!this.timePicker)
  406. this.endDate = this.endDate.endOf('day');
  407. if (this.timePicker && this.timePickerIncrement)
  408. this.endDate.minute(Math.round(this.endDate.minute() / this.timePickerIncrement) * this.timePickerIncrement);
  409. if (this.endDate.isBefore(this.startDate))
  410. this.endDate = this.startDate.clone();
  411. if (this.maxDate && this.endDate.isAfter(this.maxDate))
  412. this.endDate = this.maxDate.clone();
  413. if (this.dateLimit && this.startDate.clone().add(this.dateLimit).isBefore(this.endDate))
  414. this.endDate = this.startDate.clone().add(this.dateLimit);
  415. this.previousRightTime = this.endDate.clone();
  416. if (!this.isShowing)
  417. this.updateElement();
  418. this.updateMonthsInView();
  419. },
  420. isInvalidDate: function() {
  421. return false;
  422. },
  423. isCustomDate: function() {
  424. return false;
  425. },
  426. updateView: function() {
  427. if (this.timePicker) {
  428. this.renderTimePicker('left');
  429. this.renderTimePicker('right');
  430. if (!this.endDate) {
  431. this.container.find('.right .calendar-time select').attr('disabled', 'disabled').addClass('disabled');
  432. } else {
  433. this.container.find('.right .calendar-time select').removeAttr('disabled').removeClass('disabled');
  434. }
  435. }
  436. if (this.endDate) {
  437. this.container.find('input[name="daterangepicker_end"]').removeClass('active');
  438. this.container.find('input[name="daterangepicker_start"]').addClass('active');
  439. } else {
  440. this.container.find('input[name="daterangepicker_end"]').addClass('active');
  441. this.container.find('input[name="daterangepicker_start"]').removeClass('active');
  442. }
  443. this.updateMonthsInView();
  444. this.updateCalendars();
  445. this.updateFormInputs();
  446. },
  447. updateMonthsInView: function() {
  448. if (this.endDate) {
  449. //if both dates are visible already, do nothing
  450. if (!this.singleDatePicker && this.leftCalendar.month && this.rightCalendar.month &&
  451. (this.startDate.format('YYYY-MM') == this.leftCalendar.month.format('YYYY-MM') || this.startDate.format('YYYY-MM') == this.rightCalendar.month.format('YYYY-MM'))
  452. &&
  453. (this.endDate.format('YYYY-MM') == this.leftCalendar.month.format('YYYY-MM') || this.endDate.format('YYYY-MM') == this.rightCalendar.month.format('YYYY-MM'))
  454. ) {
  455. return;
  456. }
  457. this.leftCalendar.month = this.startDate.clone().date(2);
  458. if (!this.linkedCalendars && (this.endDate.month() != this.startDate.month() || this.endDate.year() != this.startDate.year())) {
  459. this.rightCalendar.month = this.endDate.clone().date(2);
  460. } else {
  461. this.rightCalendar.month = this.startDate.clone().date(2).add(1, 'month');
  462. }
  463. } else {
  464. if (this.leftCalendar.month.format('YYYY-MM') != this.startDate.format('YYYY-MM') && this.rightCalendar.month.format('YYYY-MM') != this.startDate.format('YYYY-MM')) {
  465. this.leftCalendar.month = this.startDate.clone().date(2);
  466. this.rightCalendar.month = this.startDate.clone().date(2).add(1, 'month');
  467. }
  468. }
  469. if (this.maxDate && this.linkedCalendars && !this.singleDatePicker && this.rightCalendar.month > this.maxDate) {
  470. this.rightCalendar.month = this.maxDate.clone().date(2);
  471. this.leftCalendar.month = this.maxDate.clone().date(2).subtract(1, 'month');
  472. }
  473. },
  474. updateCalendars: function() {
  475. if (this.timePicker) {
  476. var hour, minute, second;
  477. if (this.endDate) {
  478. hour = parseInt(this.container.find('.left .hourselect').val(), 10);
  479. minute = parseInt(this.container.find('.left .minuteselect').val(), 10);
  480. second = this.timePickerSeconds ? parseInt(this.container.find('.left .secondselect').val(), 10) : 0;
  481. if (!this.timePicker24Hour) {
  482. var ampm = this.container.find('.left .ampmselect').val();
  483. if (ampm === 'PM' && hour < 12)
  484. hour += 12;
  485. if (ampm === 'AM' && hour === 12)
  486. hour = 0;
  487. }
  488. } else {
  489. hour = parseInt(this.container.find('.right .hourselect').val(), 10);
  490. minute = parseInt(this.container.find('.right .minuteselect').val(), 10);
  491. second = this.timePickerSeconds ? parseInt(this.container.find('.right .secondselect').val(), 10) : 0;
  492. if (!this.timePicker24Hour) {
  493. var ampm = this.container.find('.right .ampmselect').val();
  494. if (ampm === 'PM' && hour < 12)
  495. hour += 12;
  496. if (ampm === 'AM' && hour === 12)
  497. hour = 0;
  498. }
  499. }
  500. this.leftCalendar.month.hour(hour).minute(minute).second(second);
  501. this.rightCalendar.month.hour(hour).minute(minute).second(second);
  502. }
  503. this.renderCalendar('left');
  504. this.renderCalendar('right');
  505. //highlight any predefined range matching the current start and end dates
  506. this.container.find('.ranges li').removeClass('active');
  507. if (this.endDate == null) return;
  508. this.calculateChosenLabel();
  509. },
  510. renderCalendar: function(side) {
  511. //
  512. // Build the matrix of dates that will populate the calendar
  513. //
  514. var calendar = side == 'left' ? this.leftCalendar : this.rightCalendar;
  515. var month = calendar.month.month();
  516. var year = calendar.month.year();
  517. var hour = calendar.month.hour();
  518. var minute = calendar.month.minute();
  519. var second = calendar.month.second();
  520. var daysInMonth = moment([year, month]).daysInMonth();
  521. var firstDay = moment([year, month, 1]);
  522. var lastDay = moment([year, month, daysInMonth]);
  523. var lastMonth = moment(firstDay).subtract(1, 'month').month();
  524. var lastYear = moment(firstDay).subtract(1, 'month').year();
  525. var daysInLastMonth = moment([lastYear, lastMonth]).daysInMonth();
  526. var dayOfWeek = firstDay.day();
  527. //initialize a 6 rows x 7 columns array for the calendar
  528. var calendar = [];
  529. calendar.firstDay = firstDay;
  530. calendar.lastDay = lastDay;
  531. for (var i = 0; i < 6; i++) {
  532. calendar[i] = [];
  533. }
  534. //populate the calendar with date objects
  535. var startDay = daysInLastMonth - dayOfWeek + this.locale.firstDay + 1;
  536. if (startDay > daysInLastMonth)
  537. startDay -= 7;
  538. if (dayOfWeek == this.locale.firstDay)
  539. startDay = daysInLastMonth - 6;
  540. var curDate = moment([lastYear, lastMonth, startDay, 12, minute, second]);
  541. var col, row;
  542. for (var i = 0, col = 0, row = 0; i < 42; i++, col++, curDate = moment(curDate).add(24, 'hour')) {
  543. if (i > 0 && col % 7 === 0) {
  544. col = 0;
  545. row++;
  546. }
  547. calendar[row][col] = curDate.clone().hour(hour).minute(minute).second(second);
  548. curDate.hour(12);
  549. if (this.minDate && calendar[row][col].format('YYYY-MM-DD') == this.minDate.format('YYYY-MM-DD') && calendar[row][col].isBefore(this.minDate) && side == 'left') {
  550. calendar[row][col] = this.minDate.clone();
  551. }
  552. if (this.maxDate && calendar[row][col].format('YYYY-MM-DD') == this.maxDate.format('YYYY-MM-DD') && calendar[row][col].isAfter(this.maxDate) && side == 'right') {
  553. calendar[row][col] = this.maxDate.clone();
  554. }
  555. }
  556. //make the calendar object available to hoverDate/clickDate
  557. if (side == 'left') {
  558. this.leftCalendar.calendar = calendar;
  559. } else {
  560. this.rightCalendar.calendar = calendar;
  561. }
  562. //
  563. // Display the calendar
  564. //
  565. var minDate = side == 'left' ? this.minDate : this.startDate;
  566. var maxDate = this.maxDate;
  567. var selected = side == 'left' ? this.startDate : this.endDate;
  568. var arrow = this.locale.direction == 'ltr' ? {left: 'chevron-left', right: 'chevron-right'} : {left: 'chevron-right', right: 'chevron-left'};
  569. var html = '<table class="table-condensed">';
  570. html += '<thead>';
  571. html += '<tr>';
  572. // add empty cell for week number
  573. if (this.showWeekNumbers || this.showISOWeekNumbers)
  574. html += '<th></th>';
  575. if ((!minDate || minDate.isBefore(calendar.firstDay)) && (!this.linkedCalendars || side == 'left')) {
  576. html += '<th class="prev available"><i class="fa fa-' + arrow.left + ' glyphicon glyphicon-' + arrow.left + '"></i></th>';
  577. } else {
  578. html += '<th></th>';
  579. }
  580. var dateHtml = this.locale.monthNames[calendar[1][1].month()] + calendar[1][1].format(" YYYY");
  581. if (this.showDropdowns) {
  582. var currentMonth = calendar[1][1].month();
  583. var currentYear = calendar[1][1].year();
  584. var maxYear = (maxDate && maxDate.year()) || (currentYear + 5);
  585. var minYear = (minDate && minDate.year()) || (currentYear - 50);
  586. var inMinYear = currentYear == minYear;
  587. var inMaxYear = currentYear == maxYear;
  588. var monthHtml = '<select class="monthselect">';
  589. for (var m = 0; m < 12; m++) {
  590. if ((!inMinYear || m >= minDate.month()) && (!inMaxYear || m <= maxDate.month())) {
  591. monthHtml += "<option value='" + m + "'" +
  592. (m === currentMonth ? " selected='selected'" : "") +
  593. ">" + this.locale.monthNames[m] + "</option>";
  594. } else {
  595. monthHtml += "<option value='" + m + "'" +
  596. (m === currentMonth ? " selected='selected'" : "") +
  597. " disabled='disabled'>" + this.locale.monthNames[m] + "</option>";
  598. }
  599. }
  600. monthHtml += "</select>";
  601. var yearHtml = '<select class="yearselect">';
  602. for (var y = minYear; y <= maxYear; y++) {
  603. yearHtml += '<option value="' + y + '"' +
  604. (y === currentYear ? ' selected="selected"' : '') +
  605. '>' + y + '</option>';
  606. }
  607. yearHtml += '</select>';
  608. dateHtml = monthHtml + yearHtml;
  609. }
  610. html += '<th colspan="5" class="month">' + dateHtml + '</th>';
  611. if ((!maxDate || maxDate.isAfter(calendar.lastDay)) && (!this.linkedCalendars || side == 'right' || this.singleDatePicker)) {
  612. html += '<th class="next available"><i class="fa fa-' + arrow.right + ' glyphicon glyphicon-' + arrow.right + '"></i></th>';
  613. } else {
  614. html += '<th></th>';
  615. }
  616. html += '</tr>';
  617. html += '<tr>';
  618. // add week number label
  619. if (this.showWeekNumbers || this.showISOWeekNumbers)
  620. html += '<th class="week">' + this.locale.weekLabel + '</th>';
  621. $.each(this.locale.daysOfWeek, function(index, dayOfWeek) {
  622. html += '<th>' + dayOfWeek + '</th>';
  623. });
  624. html += '</tr>';
  625. html += '</thead>';
  626. html += '<tbody>';
  627. //adjust maxDate to reflect the dateLimit setting in order to
  628. //grey out end dates beyond the dateLimit
  629. if (this.endDate == null && this.dateLimit) {
  630. var maxLimit = this.startDate.clone().add(this.dateLimit).endOf('day');
  631. if (!maxDate || maxLimit.isBefore(maxDate)) {
  632. maxDate = maxLimit;
  633. }
  634. }
  635. for (var row = 0; row < 6; row++) {
  636. html += '<tr>';
  637. // add week number
  638. if (this.showWeekNumbers)
  639. html += '<td class="week">' + calendar[row][0].week() + '</td>';
  640. else if (this.showISOWeekNumbers)
  641. html += '<td class="week">' + calendar[row][0].isoWeek() + '</td>';
  642. for (var col = 0; col < 7; col++) {
  643. var classes = [];
  644. //highlight today's date
  645. if (calendar[row][col].isSame(new Date(), "day"))
  646. classes.push('today');
  647. //highlight weekends
  648. if (calendar[row][col].isoWeekday() > 5)
  649. classes.push('weekend');
  650. //grey out the dates in other months displayed at beginning and end of this calendar
  651. if (calendar[row][col].month() != calendar[1][1].month())
  652. classes.push('off');
  653. //don't allow selection of dates before the minimum date
  654. if (this.minDate && calendar[row][col].isBefore(this.minDate, 'day'))
  655. classes.push('off', 'disabled');
  656. //don't allow selection of dates after the maximum date
  657. if (maxDate && calendar[row][col].isAfter(maxDate, 'day'))
  658. classes.push('off', 'disabled');
  659. //don't allow selection of date if a custom function decides it's invalid
  660. if (this.isInvalidDate(calendar[row][col]))
  661. classes.push('off', 'disabled');
  662. //highlight the currently selected start date
  663. if (calendar[row][col].format('YYYY-MM-DD') == this.startDate.format('YYYY-MM-DD'))
  664. classes.push('active', 'start-date');
  665. //highlight the currently selected end date
  666. if (this.endDate != null && calendar[row][col].format('YYYY-MM-DD') == this.endDate.format('YYYY-MM-DD'))
  667. classes.push('active', 'end-date');
  668. //highlight dates in-between the selected dates
  669. if (this.endDate != null && calendar[row][col] > this.startDate && calendar[row][col] < this.endDate)
  670. classes.push('in-range');
  671. //apply custom classes for this date
  672. var isCustom = this.isCustomDate(calendar[row][col]);
  673. if (isCustom !== false) {
  674. if (typeof isCustom === 'string')
  675. classes.push(isCustom);
  676. else
  677. Array.prototype.push.apply(classes, isCustom);
  678. }
  679. var cname = '', disabled = false;
  680. for (var i = 0; i < classes.length; i++) {
  681. cname += classes[i] + ' ';
  682. if (classes[i] == 'disabled')
  683. disabled = true;
  684. }
  685. if (!disabled)
  686. cname += 'available';
  687. html += '<td class="' + cname.replace(/^\s+|\s+$/g, '') + '" data-title="' + 'r' + row + 'c' + col + '">' + calendar[row][col].date() + '</td>';
  688. }
  689. html += '</tr>';
  690. }
  691. html += '</tbody>';
  692. html += '</table>';
  693. this.container.find('.calendar.' + side + ' .calendar-table').html(html);
  694. },
  695. renderTimePicker: function(side) {
  696. // Don't bother updating the time picker if it's currently disabled
  697. // because an end date hasn't been clicked yet
  698. if (side == 'right' && !this.endDate) return;
  699. var html, selected, minDate, maxDate = this.maxDate;
  700. if (this.dateLimit && (!this.maxDate || this.startDate.clone().add(this.dateLimit).isAfter(this.maxDate)))
  701. maxDate = this.startDate.clone().add(this.dateLimit);
  702. if (side == 'left') {
  703. selected = this.startDate.clone();
  704. minDate = this.minDate;
  705. } else if (side == 'right') {
  706. selected = this.endDate.clone();
  707. minDate = this.startDate;
  708. //Preserve the time already selected
  709. var timeSelector = this.container.find('.calendar.right .calendar-time div');
  710. if (!this.endDate && timeSelector.html() != '') {
  711. selected.hour(timeSelector.find('.hourselect option:selected').val() || selected.hour());
  712. selected.minute(timeSelector.find('.minuteselect option:selected').val() || selected.minute());
  713. selected.second(timeSelector.find('.secondselect option:selected').val() || selected.second());
  714. if (!this.timePicker24Hour) {
  715. var ampm = timeSelector.find('.ampmselect option:selected').val();
  716. if (ampm === 'PM' && selected.hour() < 12)
  717. selected.hour(selected.hour() + 12);
  718. if (ampm === 'AM' && selected.hour() === 12)
  719. selected.hour(0);
  720. }
  721. }
  722. if (selected.isBefore(this.startDate))
  723. selected = this.startDate.clone();
  724. if (maxDate && selected.isAfter(maxDate))
  725. selected = maxDate.clone();
  726. }
  727. //
  728. // hours
  729. //
  730. html = '<select class="hourselect">';
  731. var start = this.timePicker24Hour ? 0 : 1;
  732. var end = this.timePicker24Hour ? 23 : 12;
  733. for (var i = start; i <= end; i++) {
  734. var i_in_24 = i;
  735. if (!this.timePicker24Hour)
  736. i_in_24 = selected.hour() >= 12 ? (i == 12 ? 12 : i + 12) : (i == 12 ? 0 : i);
  737. var time = selected.clone().hour(i_in_24);
  738. var disabled = false;
  739. if (minDate && time.minute(59).isBefore(minDate))
  740. disabled = true;
  741. if (maxDate && time.minute(0).isAfter(maxDate))
  742. disabled = true;
  743. if (i_in_24 == selected.hour() && !disabled) {
  744. html += '<option value="' + i + '" selected="selected">' + i + '</option>';
  745. } else if (disabled) {
  746. html += '<option value="' + i + '" disabled="disabled" class="disabled">' + i + '</option>';
  747. } else {
  748. html += '<option value="' + i + '">' + i + '</option>';
  749. }
  750. }
  751. html += '</select> ';
  752. //
  753. // minutes
  754. //
  755. html += ': <select class="minuteselect">';
  756. for (var i = 0; i < 60; i += this.timePickerIncrement) {
  757. var padded = i < 10 ? '0' + i : i;
  758. var time = selected.clone().minute(i);
  759. var disabled = false;
  760. if (minDate && time.second(59).isBefore(minDate))
  761. disabled = true;
  762. if (maxDate && time.second(0).isAfter(maxDate))
  763. disabled = true;
  764. if (selected.minute() == i && !disabled) {
  765. html += '<option value="' + i + '" selected="selected">' + padded + '</option>';
  766. } else if (disabled) {
  767. html += '<option value="' + i + '" disabled="disabled" class="disabled">' + padded + '</option>';
  768. } else {
  769. html += '<option value="' + i + '">' + padded + '</option>';
  770. }
  771. }
  772. html += '</select> ';
  773. //
  774. // seconds
  775. //
  776. if (this.timePickerSeconds) {
  777. html += ': <select class="secondselect">';
  778. for (var i = 0; i < 60; i++) {
  779. var padded = i < 10 ? '0' + i : i;
  780. var time = selected.clone().second(i);
  781. var disabled = false;
  782. if (minDate && time.isBefore(minDate))
  783. disabled = true;
  784. if (maxDate && time.isAfter(maxDate))
  785. disabled = true;
  786. if (selected.second() == i && !disabled) {
  787. html += '<option value="' + i + '" selected="selected">' + padded + '</option>';
  788. } else if (disabled) {
  789. html += '<option value="' + i + '" disabled="disabled" class="disabled">' + padded + '</option>';
  790. } else {
  791. html += '<option value="' + i + '">' + padded + '</option>';
  792. }
  793. }
  794. html += '</select> ';
  795. }
  796. //
  797. // AM/PM
  798. //
  799. if (!this.timePicker24Hour) {
  800. html += '<select class="ampmselect">';
  801. var am_html = '';
  802. var pm_html = '';
  803. if (minDate && selected.clone().hour(12).minute(0).second(0).isBefore(minDate))
  804. am_html = ' disabled="disabled" class="disabled"';
  805. if (maxDate && selected.clone().hour(0).minute(0).second(0).isAfter(maxDate))
  806. pm_html = ' disabled="disabled" class="disabled"';
  807. if (selected.hour() >= 12) {
  808. html += '<option value="AM"' + am_html + '>AM</option><option value="PM" selected="selected"' + pm_html + '>PM</option>';
  809. } else {
  810. html += '<option value="AM" selected="selected"' + am_html + '>AM</option><option value="PM"' + pm_html + '>PM</option>';
  811. }
  812. html += '</select>';
  813. }
  814. this.container.find('.calendar.' + side + ' .calendar-time div').html(html);
  815. },
  816. updateFormInputs: function() {
  817. //ignore mouse movements while an above-calendar text input has focus
  818. if (this.container.find('input[name=daterangepicker_start]').is(":focus") || this.container.find('input[name=daterangepicker_end]').is(":focus"))
  819. return;
  820. this.container.find('input[name=daterangepicker_start]').val(this.startDate.format(this.locale.format));
  821. if (this.endDate)
  822. this.container.find('input[name=daterangepicker_end]').val(this.endDate.format(this.locale.format));
  823. if (this.singleDatePicker || (this.endDate && (this.startDate.isBefore(this.endDate) || this.startDate.isSame(this.endDate)))) {
  824. this.container.find('button.applyBtn').removeAttr('disabled');
  825. } else {
  826. this.container.find('button.applyBtn').attr('disabled', 'disabled');
  827. }
  828. },
  829. move: function() {
  830. var parentOffset = { top: 0, left: 0 },
  831. containerTop;
  832. var parentRightEdge = $(window).width();
  833. if (!this.parentEl.is('body')) {
  834. parentOffset = {
  835. top: this.parentEl.offset().top - this.parentEl.scrollTop(),
  836. left: this.parentEl.offset().left - this.parentEl.scrollLeft()
  837. };
  838. parentRightEdge = this.parentEl[0].clientWidth + this.parentEl.offset().left;
  839. }
  840. if (this.drops == 'up')
  841. containerTop = this.element.offset().top - this.container.outerHeight() - parentOffset.top;
  842. else
  843. containerTop = this.element.offset().top + this.element.outerHeight() - parentOffset.top;
  844. this.container[this.drops == 'up' ? 'addClass' : 'removeClass']('dropup');
  845. if (this.opens == 'left') {
  846. this.container.css({
  847. top: containerTop,
  848. right: parentRightEdge - this.element.offset().left - this.element.outerWidth(),
  849. left: 'auto'
  850. });
  851. if (this.container.offset().left < 0) {
  852. this.container.css({
  853. right: 'auto',
  854. left: 9
  855. });
  856. }
  857. } else if (this.opens == 'center') {
  858. this.container.css({
  859. top: containerTop,
  860. left: this.element.offset().left - parentOffset.left + this.element.outerWidth() / 2
  861. - this.container.outerWidth() / 2,
  862. right: 'auto'
  863. });
  864. if (this.container.offset().left < 0) {
  865. this.container.css({
  866. right: 'auto',
  867. left: 9
  868. });
  869. }
  870. } else {
  871. this.container.css({
  872. top: containerTop,
  873. left: this.element.offset().left - parentOffset.left,
  874. right: 'auto'
  875. });
  876. if (this.container.offset().left + this.container.outerWidth() > $(window).width()) {
  877. this.container.css({
  878. left: 'auto',
  879. right: 0
  880. });
  881. }
  882. }
  883. },
  884. show: function(e) {
  885. if (this.isShowing) return;
  886. // Create a click proxy that is private to this instance of datepicker, for unbinding
  887. this._outsideClickProxy = $.proxy(function(e) { this.outsideClick(e); }, this);
  888. // Bind global datepicker mousedown for hiding and
  889. $(document)
  890. .on('mousedown.daterangepicker', this._outsideClickProxy)
  891. // also support mobile devices
  892. .on('touchend.daterangepicker', this._outsideClickProxy)
  893. // also explicitly play nice with Bootstrap dropdowns, which stopPropagation when clicking them
  894. .on('click.daterangepicker', '[data-toggle=dropdown]', this._outsideClickProxy)
  895. // and also close when focus changes to outside the picker (eg. tabbing between controls)
  896. .on('focusin.daterangepicker', this._outsideClickProxy);
  897. // Reposition the picker if the window is resized while it's open
  898. $(window).on('resize.daterangepicker', $.proxy(function(e) { this.move(e); }, this));
  899. this.oldStartDate = this.startDate.clone();
  900. this.oldEndDate = this.endDate.clone();
  901. this.previousRightTime = this.endDate.clone();
  902. this.updateView();
  903. this.container.show();
  904. this.move();
  905. this.element.trigger('show.daterangepicker', this);
  906. this.isShowing = true;
  907. },
  908. hide: function(e) {
  909. if (!this.isShowing) return;
  910. //incomplete date selection, revert to last values
  911. if (!this.endDate) {
  912. this.startDate = this.oldStartDate.clone();
  913. this.endDate = this.oldEndDate.clone();
  914. }
  915. //if a new date range was selected, invoke the user callback function
  916. if (!this.startDate.isSame(this.oldStartDate) || !this.endDate.isSame(this.oldEndDate))
  917. this.callback(this.startDate, this.endDate, this.chosenLabel);
  918. //if picker is attached to a text input, update it
  919. this.updateElement();
  920. $(document).off('.daterangepicker');
  921. $(window).off('.daterangepicker');
  922. this.container.hide();
  923. this.element.trigger('hide.daterangepicker', this);
  924. this.isShowing = false;
  925. },
  926. toggle: function(e) {
  927. if (this.isShowing) {
  928. this.hide();
  929. } else {
  930. this.show();
  931. }
  932. },
  933. outsideClick: function(e) {
  934. var target = $(e.target);
  935. // if the page is clicked anywhere except within the daterangerpicker/button
  936. // itself then call this.hide()
  937. if (
  938. // ie modal dialog fix
  939. e.type == "focusin" ||
  940. target.closest(this.element).length ||
  941. target.closest(this.container).length ||
  942. target.closest('.calendar-table').length
  943. ) return;
  944. this.hide();
  945. this.element.trigger('outsideClick.daterangepicker', this);
  946. },
  947. showCalendars: function() {
  948. this.container.addClass('show-calendar');
  949. this.move();
  950. this.element.trigger('showCalendar.daterangepicker', this);
  951. },
  952. hideCalendars: function() {
  953. this.container.removeClass('show-calendar');
  954. this.element.trigger('hideCalendar.daterangepicker', this);
  955. },
  956. hoverRange: function(e) {
  957. //ignore mouse movements while an above-calendar text input has focus
  958. if (this.container.find('input[name=daterangepicker_start]').is(":focus") || this.container.find('input[name=daterangepicker_end]').is(":focus"))
  959. return;
  960. var label = e.target.getAttribute('data-range-key');
  961. if (label == this.locale.customRangeLabel) {
  962. this.updateView();
  963. } else {
  964. var dates = this.ranges[label];
  965. this.container.find('input[name=daterangepicker_start]').val(dates[0].format(this.locale.format));
  966. this.container.find('input[name=daterangepicker_end]').val(dates[1].format(this.locale.format));
  967. }
  968. },
  969. clickRange: function(e) {
  970. var label = e.target.getAttribute('data-range-key');
  971. this.chosenLabel = label;
  972. if (label == this.locale.customRangeLabel) {
  973. this.showCalendars();
  974. } else {
  975. var dates = this.ranges[label];
  976. this.startDate = dates[0];
  977. this.endDate = dates[1];
  978. if (!this.timePicker) {
  979. this.startDate.startOf('day');
  980. this.endDate.endOf('day');
  981. }
  982. if (!this.alwaysShowCalendars)
  983. this.hideCalendars();
  984. this.clickApply();
  985. }
  986. },
  987. clickPrev: function(e) {
  988. var cal = $(e.target).parents('.calendar');
  989. if (cal.hasClass('left')) {
  990. this.leftCalendar.month.subtract(1, 'month');
  991. if (this.linkedCalendars)
  992. this.rightCalendar.month.subtract(1, 'month');
  993. } else {
  994. this.rightCalendar.month.subtract(1, 'month');
  995. }
  996. this.updateCalendars();
  997. },
  998. clickNext: function(e) {
  999. var cal = $(e.target).parents('.calendar');
  1000. if (cal.hasClass('left')) {
  1001. this.leftCalendar.month.add(1, 'month');
  1002. } else {
  1003. this.rightCalendar.month.add(1, 'month');
  1004. if (this.linkedCalendars)
  1005. this.leftCalendar.month.add(1, 'month');
  1006. }
  1007. this.updateCalendars();
  1008. },
  1009. hoverDate: function(e) {
  1010. //ignore mouse movements while an above-calendar text input has focus
  1011. //if (this.container.find('input[name=daterangepicker_start]').is(":focus") || this.container.find('input[name=daterangepicker_end]').is(":focus"))
  1012. // return;
  1013. //ignore dates that can't be selected
  1014. if (!$(e.target).hasClass('available')) return;
  1015. //have the text inputs above calendars reflect the date being hovered over
  1016. var title = $(e.target).attr('data-title');
  1017. var row = title.substr(1, 1);
  1018. var col = title.substr(3, 1);
  1019. var cal = $(e.target).parents('.calendar');
  1020. var date = cal.hasClass('left') ? this.leftCalendar.calendar[row][col] : this.rightCalendar.calendar[row][col];
  1021. if (this.endDate && !this.container.find('input[name=daterangepicker_start]').is(":focus")) {
  1022. this.container.find('input[name=daterangepicker_start]').val(date.format(this.locale.format));
  1023. } else if (!this.endDate && !this.container.find('input[name=daterangepicker_end]').is(":focus")) {
  1024. this.container.find('input[name=daterangepicker_end]').val(date.format(this.locale.format));
  1025. }
  1026. //highlight the dates between the start date and the date being hovered as a potential end date
  1027. var leftCalendar = this.leftCalendar;
  1028. var rightCalendar = this.rightCalendar;
  1029. var startDate = this.startDate;
  1030. if (!this.endDate) {
  1031. this.container.find('.calendar td').each(function(index, el) {
  1032. //skip week numbers, only look at dates
  1033. if ($(el).hasClass('week')) return;
  1034. var title = $(el).attr('data-title');
  1035. var row = title.substr(1, 1);
  1036. var col = title.substr(3, 1);
  1037. var cal = $(el).parents('.calendar');
  1038. var dt = cal.hasClass('left') ? leftCalendar.calendar[row][col] : rightCalendar.calendar[row][col];
  1039. if ((dt.isAfter(startDate) && dt.isBefore(date)) || dt.isSame(date, 'day')) {
  1040. $(el).addClass('in-range');
  1041. } else {
  1042. $(el).removeClass('in-range');
  1043. }
  1044. });
  1045. }
  1046. },
  1047. clickDate: function(e) {
  1048. if (!$(e.target).hasClass('available')) return;
  1049. var title = $(e.target).attr('data-title');
  1050. var row = title.substr(1, 1);
  1051. var col = title.substr(3, 1);
  1052. var cal = $(e.target).parents('.calendar');
  1053. var date = cal.hasClass('left') ? this.leftCalendar.calendar[row][col] : this.rightCalendar.calendar[row][col];
  1054. //
  1055. // this function needs to do a few things:
  1056. // * alternate between selecting a start and end date for the range,
  1057. // * if the time picker is enabled, apply the hour/minute/second from the select boxes to the clicked date
  1058. // * if autoapply is enabled, and an end date was chosen, apply the selection
  1059. // * if single date picker mode, and time picker isn't enabled, apply the selection immediately
  1060. // * if one of the inputs above the calendars was focused, cancel that manual input
  1061. //
  1062. if (this.endDate || date.isBefore(this.startDate, 'day')) { //picking start
  1063. if (this.timePicker) {
  1064. var hour = parseInt(this.container.find('.left .hourselect').val(), 10);
  1065. if (!this.timePicker24Hour) {
  1066. var ampm = this.container.find('.left .ampmselect').val();
  1067. if (ampm === 'PM' && hour < 12)
  1068. hour += 12;
  1069. if (ampm === 'AM' && hour === 12)
  1070. hour = 0;
  1071. }
  1072. var minute = parseInt(this.container.find('.left .minuteselect').val(), 10);
  1073. var second = this.timePickerSeconds ? parseInt(this.container.find('.left .secondselect').val(), 10) : 0;
  1074. date = date.clone().hour(hour).minute(minute).second(second);
  1075. }
  1076. this.endDate = null;
  1077. this.setStartDate(date.clone());
  1078. } else if (!this.endDate && date.isBefore(this.startDate)) {
  1079. //special case: clicking the same date for start/end,
  1080. //but the time of the end date is before the start date
  1081. this.setEndDate(this.startDate.clone());
  1082. } else { // picking end
  1083. if (this.timePicker) {
  1084. var hour = parseInt(this.container.find('.right .hourselect').val(), 10);
  1085. if (!this.timePicker24Hour) {
  1086. var ampm = this.container.find('.right .ampmselect').val();
  1087. if (ampm === 'PM' && hour < 12)
  1088. hour += 12;
  1089. if (ampm === 'AM' && hour === 12)
  1090. hour = 0;
  1091. }
  1092. var minute = parseInt(this.container.find('.right .minuteselect').val(), 10);
  1093. var second = this.timePickerSeconds ? parseInt(this.container.find('.right .secondselect').val(), 10) : 0;
  1094. date = date.clone().hour(hour).minute(minute).second(second);
  1095. }
  1096. this.setEndDate(date.clone());
  1097. if (this.autoApply) {
  1098. this.calculateChosenLabel();
  1099. this.clickApply();
  1100. }
  1101. }
  1102. if (this.singleDatePicker) {
  1103. this.setEndDate(this.startDate);
  1104. if (!this.timePicker)
  1105. this.clickApply();
  1106. }
  1107. this.updateView();
  1108. //This is to cancel the blur event handler if the mouse was in one of the inputs
  1109. e.stopPropagation();
  1110. },
  1111. calculateChosenLabel: function () {
  1112. var customRange = true;
  1113. var i = 0;
  1114. for (var range in this.ranges) {
  1115. if (this.timePicker) {
  1116. if (this.startDate.isSame(this.ranges[range][0]) && this.endDate.isSame(this.ranges[range][1])) {
  1117. customRange = false;
  1118. this.chosenLabel = this.container.find('.ranges li:eq(' + i + ')').addClass('active').html();
  1119. break;
  1120. }
  1121. } else {
  1122. //ignore times when comparing dates if time picker is not enabled
  1123. if (this.startDate.format('YYYY-MM-DD') == this.ranges[range][0].format('YYYY-MM-DD') && this.endDate.format('YYYY-MM-DD') == this.ranges[range][1].format('YYYY-MM-DD')) {
  1124. customRange = false;
  1125. this.chosenLabel = this.container.find('.ranges li:eq(' + i + ')').addClass('active').html();
  1126. break;
  1127. }
  1128. }
  1129. i++;
  1130. }
  1131. if (customRange) {
  1132. if (this.showCustomRangeLabel) {
  1133. this.chosenLabel = this.container.find('.ranges li:last').addClass('active').html();
  1134. } else {
  1135. this.chosenLabel = null;
  1136. }
  1137. this.showCalendars();
  1138. }
  1139. },
  1140. clickApply: function(e) {
  1141. this.hide();
  1142. this.element.trigger('apply.daterangepicker', this);
  1143. },
  1144. clickCancel: function(e) {
  1145. this.startDate = this.oldStartDate;
  1146. this.endDate = this.oldEndDate;
  1147. this.hide();
  1148. this.element.trigger('cancel.daterangepicker', this);
  1149. },
  1150. monthOrYearChanged: function(e) {
  1151. var isLeft = $(e.target).closest('.calendar').hasClass('left'),
  1152. leftOrRight = isLeft ? 'left' : 'right',
  1153. cal = this.container.find('.calendar.'+leftOrRight);
  1154. // Month must be Number for new moment versions
  1155. var month = parseInt(cal.find('.monthselect').val(), 10);
  1156. var year = cal.find('.yearselect').val();
  1157. if (!isLeft) {
  1158. if (year < this.startDate.year() || (year == this.startDate.year() && month < this.startDate.month())) {
  1159. month = this.startDate.month();
  1160. year = this.startDate.year();
  1161. }
  1162. }
  1163. if (this.minDate) {
  1164. if (year < this.minDate.year() || (year == this.minDate.year() && month < this.minDate.month())) {
  1165. month = this.minDate.month();
  1166. year = this.minDate.year();
  1167. }
  1168. }
  1169. if (this.maxDate) {
  1170. if (year > this.maxDate.year() || (year == this.maxDate.year() && month > this.maxDate.month())) {
  1171. month = this.maxDate.month();
  1172. year = this.maxDate.year();
  1173. }
  1174. }
  1175. if (isLeft) {
  1176. this.leftCalendar.month.month(month).year(year);
  1177. if (this.linkedCalendars)
  1178. this.rightCalendar.month = this.leftCalendar.month.clone().add(1, 'month');
  1179. } else {
  1180. this.rightCalendar.month.month(month).year(year);
  1181. if (this.linkedCalendars)
  1182. this.leftCalendar.month = this.rightCalendar.month.clone().subtract(1, 'month');
  1183. }
  1184. this.updateCalendars();
  1185. },
  1186. timeChanged: function(e) {
  1187. var cal = $(e.target).closest('.calendar'),
  1188. isLeft = cal.hasClass('left');
  1189. var hour = parseInt(cal.find('.hourselect').val(), 10);
  1190. var minute = parseInt(cal.find('.minuteselect').val(), 10);
  1191. var second = this.timePickerSeconds ? parseInt(cal.find('.secondselect').val(), 10) : 0;
  1192. if (!this.timePicker24Hour) {
  1193. var ampm = cal.find('.ampmselect').val();
  1194. if (ampm === 'PM' && hour < 12)
  1195. hour += 12;
  1196. if (ampm === 'AM' && hour === 12)
  1197. hour = 0;
  1198. }
  1199. if (isLeft) {
  1200. var start = this.startDate.clone();
  1201. start.hour(hour);
  1202. start.minute(minute);
  1203. start.second(second);
  1204. this.setStartDate(start);
  1205. if (this.singleDatePicker) {
  1206. this.endDate = this.startDate.clone();
  1207. } else if (this.endDate && this.endDate.format('YYYY-MM-DD') == start.format('YYYY-MM-DD') && this.endDate.isBefore(start)) {
  1208. this.setEndDate(start.clone());
  1209. }
  1210. } else if (this.endDate) {
  1211. var end = this.endDate.clone();
  1212. end.hour(hour);
  1213. end.minute(minute);
  1214. end.second(second);
  1215. this.setEndDate(end);
  1216. }
  1217. //update the calendars so all clickable dates reflect the new time component
  1218. this.updateCalendars();
  1219. //update the form inputs above the calendars with the new time
  1220. this.updateFormInputs();
  1221. //re-render the time pickers because changing one selection can affect what's enabled in another
  1222. this.renderTimePicker('left');
  1223. this.renderTimePicker('right');
  1224. },
  1225. formInputsChanged: function(e) {
  1226. var isRight = $(e.target).closest('.calendar').hasClass('right');
  1227. var start = moment(this.container.find('input[name="daterangepicker_start"]').val(), this.locale.format);
  1228. var end = moment(this.container.find('input[name="daterangepicker_end"]').val(), this.locale.format);
  1229. if (start.isValid() && end.isValid()) {
  1230. if (isRight && end.isBefore(start))
  1231. start = end.clone();
  1232. this.setStartDate(start);
  1233. this.setEndDate(end);
  1234. if (isRight) {
  1235. this.container.find('input[name="daterangepicker_start"]').val(this.startDate.format(this.locale.format));
  1236. } else {
  1237. this.container.find('input[name="daterangepicker_end"]').val(this.endDate.format(this.locale.format));
  1238. }
  1239. }
  1240. this.updateView();
  1241. },
  1242. formInputsFocused: function(e) {
  1243. // Highlight the focused input
  1244. this.container.find('input[name="daterangepicker_start"], input[name="daterangepicker_end"]').removeClass('active');
  1245. $(e.target).addClass('active');
  1246. // Set the state such that if the user goes back to using a mouse,
  1247. // the calendars are aware we're selecting the end of the range, not
  1248. // the start. This allows someone to edit the end of a date range without
  1249. // re-selecting the beginning, by clicking on the end date input then
  1250. // using the calendar.
  1251. var isRight = $(e.target).closest('.calendar').hasClass('right');
  1252. if (isRight) {
  1253. this.endDate = null;
  1254. this.setStartDate(this.startDate.clone());
  1255. this.updateView();
  1256. }
  1257. },
  1258. formInputsBlurred: function(e) {
  1259. // this function has one purpose right now: if you tab from the first
  1260. // text input to the second in the UI, the endDate is nulled so that
  1261. // you can click another, but if you tab out without clicking anything
  1262. // or changing the input value, the old endDate should be retained
  1263. if (!this.endDate) {
  1264. var val = this.container.find('input[name="daterangepicker_end"]').val();
  1265. var end = moment(val, this.locale.format);
  1266. if (end.isValid()) {
  1267. this.setEndDate(end);
  1268. this.updateView();
  1269. }
  1270. }
  1271. },
  1272. elementChanged: function() {
  1273. if (!this.element.is('input')) return;
  1274. if (!this.element.val().length) return;
  1275. if (this.element.val().length < this.locale.format.length) return;
  1276. var dateString = this.element.val().split(this.locale.separator),
  1277. start = null,
  1278. end = null;
  1279. if (dateString.length === 2) {
  1280. start = moment(dateString[0], this.locale.format);
  1281. end = moment(dateString[1], this.locale.format);
  1282. }
  1283. if (this.singleDatePicker || start === null || end === null) {
  1284. start = moment(this.element.val(), this.locale.format);
  1285. end = start;
  1286. }
  1287. if (!start.isValid() || !end.isValid()) return;
  1288. this.setStartDate(start);
  1289. this.setEndDate(end);
  1290. this.updateView();
  1291. },
  1292. keydown: function(e) {
  1293. //hide on tab or enter
  1294. if ((e.keyCode === 9) || (e.keyCode === 13)) {
  1295. this.hide();
  1296. }
  1297. },
  1298. updateElement: function() {
  1299. if (this.element.is('input') && !this.singleDatePicker && this.autoUpdateInput) {
  1300. this.element.val(this.startDate.format(this.locale.format) + this.locale.separator + this.endDate.format(this.locale.format));
  1301. this.element.trigger('change');
  1302. } else if (this.element.is('input') && this.autoUpdateInput) {
  1303. this.element.val(this.startDate.format(this.locale.format));
  1304. this.element.trigger('change');
  1305. }
  1306. },
  1307. remove: function() {
  1308. this.container.remove();
  1309. this.element.off('.daterangepicker');
  1310. this.element.removeData();
  1311. }
  1312. };
  1313. $.fn.daterangepicker = function(options, callback) {
  1314. this.each(function() {
  1315. var el = $(this);
  1316. if (el.data('daterangepicker'))
  1317. el.data('daterangepicker').remove();
  1318. el.data('daterangepicker', new DateRangePicker(el, options, callback));
  1319. });
  1320. return this;
  1321. };
  1322. return DateRangePicker;
  1323. }));