daterangepicker.js 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254
  1. /**
  2. * @version: 1.3.17
  3. * @author: Dan Grossman http://www.dangrossman.info/
  4. * @date: 2014-11-25
  5. * @copyright: Copyright (c) 2012-2014 Dan Grossman. All rights reserved.
  6. * @license: Licensed under the MIT license. See http://www.opensource.org/licenses/mit-license.php
  7. * @website: http://www.improvely.com/
  8. */
  9. (function(root, factory) {
  10. if (typeof define === 'function' && define.amd) {
  11. define(['moment', 'jquery', 'exports'], function(momentjs, $, exports) {
  12. root.daterangepicker = factory(root, exports, momentjs, $);
  13. });
  14. } else if (typeof exports !== 'undefined') {
  15. var momentjs = require('moment');
  16. var jQuery;
  17. try {
  18. jQuery = require('jquery');
  19. } catch (err) {
  20. jQuery = window.jQuery;
  21. if (!jQuery) throw new Error('jQuery dependency not found');
  22. }
  23. factory(root, exports, momentjs, jQuery);
  24. // Finally, as a browser global.
  25. } else {
  26. root.daterangepicker = factory(root, {}, root.moment, (root.jQuery || root.Zepto || root.ender || root.$));
  27. }
  28. }(this, function(root, daterangepicker, moment, $) {
  29. var DateRangePicker = function (element, options, cb) {
  30. // by default, the daterangepicker element is placed at the bottom of HTML body
  31. this.parentEl = 'body';
  32. //element that triggered the date range picker
  33. this.element = $(element);
  34. //tracks visible state
  35. this.isShowing = false;
  36. //create the picker HTML object
  37. var DRPTemplate = '<div class="daterangepicker dropdown-menu">' +
  38. '<div class="calendar first left"></div>' +
  39. '<div class="calendar second right"></div>' +
  40. '<div class="ranges">' +
  41. '<div class="range_inputs">' +
  42. '<div class="daterangepicker_start_input">' +
  43. '<label for="daterangepicker_start"></label>' +
  44. '<input class="input-mini" type="text" name="daterangepicker_start" value="" />' +
  45. '</div>' +
  46. '<div class="daterangepicker_end_input">' +
  47. '<label for="daterangepicker_end"></label>' +
  48. '<input class="input-mini" type="text" name="daterangepicker_end" value="" />' +
  49. '</div>' +
  50. '<button class="applyBtn" disabled="disabled"></button>&nbsp;' +
  51. '<button class="cancelBtn"></button>' +
  52. '</div>' +
  53. '</div>' +
  54. '</div>';
  55. //custom options
  56. if (typeof options !== 'object' || options === null)
  57. options = {};
  58. this.parentEl = (typeof options === 'object' && options.parentEl && $(options.parentEl).length) ? $(options.parentEl) : $(this.parentEl);
  59. this.container = $(DRPTemplate).appendTo(this.parentEl);
  60. this.setOptions(options, cb);
  61. //apply CSS classes and labels to buttons
  62. var c = this.container;
  63. $.each(this.buttonClasses, function (idx, val) {
  64. c.find('button').addClass(val);
  65. });
  66. this.container.find('.daterangepicker_start_input label').html(this.locale.fromLabel);
  67. this.container.find('.daterangepicker_end_input label').html(this.locale.toLabel);
  68. if (this.applyClass.length)
  69. this.container.find('.applyBtn').addClass(this.applyClass);
  70. if (this.cancelClass.length)
  71. this.container.find('.cancelBtn').addClass(this.cancelClass);
  72. this.container.find('.applyBtn').html(this.locale.applyLabel);
  73. this.container.find('.cancelBtn').html(this.locale.cancelLabel);
  74. //event listeners
  75. this.container.find('.calendar')
  76. .on('click.daterangepicker', '.prev', $.proxy(this.clickPrev, this))
  77. .on('click.daterangepicker', '.next', $.proxy(this.clickNext, this))
  78. .on('click.daterangepicker', 'td.available', $.proxy(this.clickDate, this))
  79. .on('mouseenter.daterangepicker', 'td.available', $.proxy(this.hoverDate, this))
  80. .on('mouseleave.daterangepicker', 'td.available', $.proxy(this.updateFormInputs, this))
  81. .on('change.daterangepicker', 'select.yearselect', $.proxy(this.updateMonthYear, this))
  82. .on('change.daterangepicker', 'select.monthselect', $.proxy(this.updateMonthYear, this))
  83. .on('change.daterangepicker', 'select.hourselect,select.minuteselect,select.secondselect,select.ampmselect', $.proxy(this.updateTime, this));
  84. this.container.find('.ranges')
  85. .on('click.daterangepicker', 'button.applyBtn', $.proxy(this.clickApply, this))
  86. .on('click.daterangepicker', 'button.cancelBtn', $.proxy(this.clickCancel, this))
  87. .on('click.daterangepicker', '.daterangepicker_start_input,.daterangepicker_end_input', $.proxy(this.showCalendars, this))
  88. .on('change.daterangepicker', '.daterangepicker_start_input,.daterangepicker_end_input', $.proxy(this.inputsChanged, this))
  89. .on('keydown.daterangepicker', '.daterangepicker_start_input,.daterangepicker_end_input', $.proxy(this.inputsKeydown, this))
  90. .on('click.daterangepicker', 'li', $.proxy(this.clickRange, this))
  91. .on('mouseenter.daterangepicker', 'li', $.proxy(this.enterRange, this))
  92. .on('mouseleave.daterangepicker', 'li', $.proxy(this.updateFormInputs, this));
  93. if (this.element.is('input')) {
  94. this.element.on({
  95. 'click.daterangepicker': $.proxy(this.show, this),
  96. 'focus.daterangepicker': $.proxy(this.show, this),
  97. 'keyup.daterangepicker': $.proxy(this.updateFromControl, this)
  98. });
  99. } else {
  100. this.element.on('click.daterangepicker', $.proxy(this.toggle, this));
  101. }
  102. };
  103. DateRangePicker.prototype = {
  104. constructor: DateRangePicker,
  105. setOptions: function(options, callback) {
  106. this.startDate = moment().startOf('day');
  107. this.endDate = moment().endOf('day');
  108. this.timeZone = moment().zone();
  109. this.minDate = false;
  110. this.maxDate = false;
  111. this.dateLimit = false;
  112. this.showDropdowns = false;
  113. this.showWeekNumbers = false;
  114. this.timePicker = false;
  115. this.timePickerSeconds = false;
  116. this.timePickerIncrement = 30;
  117. this.timePicker12Hour = true;
  118. this.singleDatePicker = false;
  119. this.ranges = {};
  120. this.opens = 'right';
  121. if (this.element.hasClass('pull-right'))
  122. this.opens = 'left';
  123. this.buttonClasses = ['btn', 'btn-small btn-sm'];
  124. this.applyClass = 'btn-success';
  125. this.cancelClass = 'btn-default';
  126. this.format = 'MM/DD/YYYY';
  127. this.separator = ' - ';
  128. this.locale = {
  129. applyLabel: 'Apply',
  130. cancelLabel: 'Cancel',
  131. fromLabel: 'From',
  132. toLabel: 'To',
  133. weekLabel: 'W',
  134. customRangeLabel: 'Custom Range',
  135. daysOfWeek: moment.weekdaysMin(),
  136. monthNames: moment.monthsShort(),
  137. firstDay: moment.localeData()._week.dow
  138. };
  139. this.cb = function () { };
  140. if (typeof options.format === 'string')
  141. this.format = options.format;
  142. if (typeof options.separator === 'string')
  143. this.separator = options.separator;
  144. if (typeof options.startDate === 'string')
  145. this.startDate = moment(options.startDate, this.format);
  146. if (typeof options.endDate === 'string')
  147. this.endDate = moment(options.endDate, this.format);
  148. if (typeof options.minDate === 'string')
  149. this.minDate = moment(options.minDate, this.format);
  150. if (typeof options.maxDate === 'string')
  151. this.maxDate = moment(options.maxDate, this.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. if (typeof options.applyClass === 'string')
  161. this.applyClass = options.applyClass;
  162. if (typeof options.cancelClass === 'string')
  163. this.cancelClass = options.cancelClass;
  164. if (typeof options.dateLimit === 'object')
  165. this.dateLimit = options.dateLimit;
  166. if (typeof options.locale === 'object') {
  167. if (typeof options.locale.daysOfWeek === 'object') {
  168. // Create a copy of daysOfWeek to avoid modification of original
  169. // options object for reusability in multiple daterangepicker instances
  170. this.locale.daysOfWeek = options.locale.daysOfWeek.slice();
  171. }
  172. if (typeof options.locale.monthNames === 'object') {
  173. this.locale.monthNames = options.locale.monthNames.slice();
  174. }
  175. if (typeof options.locale.firstDay === 'number') {
  176. this.locale.firstDay = options.locale.firstDay;
  177. }
  178. if (typeof options.locale.applyLabel === 'string') {
  179. this.locale.applyLabel = options.locale.applyLabel;
  180. }
  181. if (typeof options.locale.cancelLabel === 'string') {
  182. this.locale.cancelLabel = options.locale.cancelLabel;
  183. }
  184. if (typeof options.locale.fromLabel === 'string') {
  185. this.locale.fromLabel = options.locale.fromLabel;
  186. }
  187. if (typeof options.locale.toLabel === 'string') {
  188. this.locale.toLabel = options.locale.toLabel;
  189. }
  190. if (typeof options.locale.weekLabel === 'string') {
  191. this.locale.weekLabel = options.locale.weekLabel;
  192. }
  193. if (typeof options.locale.customRangeLabel === 'string') {
  194. this.locale.customRangeLabel = options.locale.customRangeLabel;
  195. }
  196. }
  197. if (typeof options.opens === 'string')
  198. this.opens = options.opens;
  199. if (typeof options.showWeekNumbers === 'boolean') {
  200. this.showWeekNumbers = options.showWeekNumbers;
  201. }
  202. if (typeof options.buttonClasses === 'string') {
  203. this.buttonClasses = [options.buttonClasses];
  204. }
  205. if (typeof options.buttonClasses === 'object') {
  206. this.buttonClasses = options.buttonClasses;
  207. }
  208. if (typeof options.showDropdowns === 'boolean') {
  209. this.showDropdowns = options.showDropdowns;
  210. }
  211. if (typeof options.singleDatePicker === 'boolean') {
  212. this.singleDatePicker = options.singleDatePicker;
  213. if (this.singleDatePicker) {
  214. this.endDate = this.startDate.clone();
  215. }
  216. }
  217. if (typeof options.timePicker === 'boolean') {
  218. this.timePicker = options.timePicker;
  219. }
  220. if (typeof options.timePickerSeconds === 'boolean') {
  221. this.timePickerSeconds = options.timePickerSeconds;
  222. }
  223. if (typeof options.timePickerIncrement === 'number') {
  224. this.timePickerIncrement = options.timePickerIncrement;
  225. }
  226. if (typeof options.timePicker12Hour === 'boolean') {
  227. this.timePicker12Hour = options.timePicker12Hour;
  228. }
  229. // update day names order to firstDay
  230. if (this.locale.firstDay != 0) {
  231. var iterator = this.locale.firstDay;
  232. while (iterator > 0) {
  233. this.locale.daysOfWeek.push(this.locale.daysOfWeek.shift());
  234. iterator--;
  235. }
  236. }
  237. var start, end, range;
  238. //if no start/end dates set, check if an input element contains initial values
  239. if (typeof options.startDate === 'undefined' && typeof options.endDate === 'undefined') {
  240. if ($(this.element).is('input[type=text]')) {
  241. var val = $(this.element).val(),
  242. split = val.split(this.separator);
  243. start = end = null;
  244. if (split.length == 2) {
  245. start = moment(split[0], this.format);
  246. end = moment(split[1], this.format);
  247. } else if (this.singleDatePicker && val !== "") {
  248. start = moment(val, this.format);
  249. end = moment(val, this.format);
  250. }
  251. if (start !== null && end !== null) {
  252. this.startDate = start;
  253. this.endDate = end;
  254. }
  255. }
  256. }
  257. // bind the time zone used to build the calendar to either the timeZone passed in through the options or the zone of the startDate (which will be the local time zone by default)
  258. if (typeof options.timeZone === 'string' || typeof options.timeZone === 'number') {
  259. this.timeZone = options.timeZone;
  260. this.startDate.zone(this.timeZone);
  261. this.endDate.zone(this.timeZone);
  262. } else {
  263. this.timeZone = moment(this.startDate).zone();
  264. }
  265. if (typeof options.ranges === 'object') {
  266. for (range in options.ranges) {
  267. if (typeof options.ranges[range][0] === 'string')
  268. start = moment(options.ranges[range][0], this.format);
  269. else
  270. start = moment(options.ranges[range][0]);
  271. if (typeof options.ranges[range][1] === 'string')
  272. end = moment(options.ranges[range][1], this.format);
  273. else
  274. end = moment(options.ranges[range][1]);
  275. // If we have a min/max date set, bound this range
  276. // to it, but only if it would otherwise fall
  277. // outside of the min/max.
  278. if (this.minDate && start.isBefore(this.minDate))
  279. start = moment(this.minDate);
  280. if (this.maxDate && end.isAfter(this.maxDate))
  281. end = moment(this.maxDate);
  282. // If the end of the range is before the minimum (if min is set) OR
  283. // the start of the range is after the max (also if set) don't display this
  284. // range option.
  285. if ((this.minDate && end.isBefore(this.minDate)) || (this.maxDate && start.isAfter(this.maxDate))) {
  286. continue;
  287. }
  288. this.ranges[range] = [start, end];
  289. }
  290. var list = '<ul>';
  291. for (range in this.ranges) {
  292. list += '<li>' + range + '</li>';
  293. }
  294. list += '<li>' + this.locale.customRangeLabel + '</li>';
  295. list += '</ul>';
  296. this.container.find('.ranges ul').remove();
  297. this.container.find('.ranges').prepend(list);
  298. }
  299. if (typeof callback === 'function') {
  300. this.cb = callback;
  301. }
  302. if (!this.timePicker) {
  303. this.startDate = this.startDate.startOf('day');
  304. this.endDate = this.endDate.endOf('day');
  305. }
  306. if (this.singleDatePicker) {
  307. this.opens = 'right';
  308. this.container.addClass('single');
  309. this.container.find('.calendar.right').show();
  310. this.container.find('.calendar.left').hide();
  311. if (!this.timePicker) {
  312. this.container.find('.ranges').hide();
  313. } else {
  314. this.container.find('.ranges .daterangepicker_start_input, .ranges .daterangepicker_end_input').hide();
  315. }
  316. if (!this.container.find('.calendar.right').hasClass('single'))
  317. this.container.find('.calendar.right').addClass('single');
  318. } else {
  319. this.container.removeClass('single');
  320. this.container.find('.calendar.right').removeClass('single');
  321. this.container.find('.ranges').show();
  322. }
  323. this.oldStartDate = this.startDate.clone();
  324. this.oldEndDate = this.endDate.clone();
  325. this.oldChosenLabel = this.chosenLabel;
  326. this.leftCalendar = {
  327. month: moment([this.startDate.year(), this.startDate.month(), 1, this.startDate.hour(), this.startDate.minute(), this.startDate.second()]),
  328. calendar: []
  329. };
  330. this.rightCalendar = {
  331. month: moment([this.endDate.year(), this.endDate.month(), 1, this.endDate.hour(), this.endDate.minute(), this.endDate.second()]),
  332. calendar: []
  333. };
  334. if (this.opens == 'right' || this.opens == 'center') {
  335. //swap calendar positions
  336. var first = this.container.find('.calendar.first');
  337. var second = this.container.find('.calendar.second');
  338. if (second.hasClass('single')) {
  339. second.removeClass('single');
  340. first.addClass('single');
  341. }
  342. first.removeClass('left').addClass('right');
  343. second.removeClass('right').addClass('left');
  344. if (this.singleDatePicker) {
  345. first.show();
  346. second.hide();
  347. }
  348. }
  349. if (typeof options.ranges === 'undefined' && !this.singleDatePicker) {
  350. this.container.addClass('show-calendar');
  351. }
  352. this.container.addClass('opens' + this.opens);
  353. this.updateView();
  354. this.updateCalendars();
  355. },
  356. setStartDate: function(startDate) {
  357. if (typeof startDate === 'string')
  358. this.startDate = moment(startDate, this.format).zone(this.timeZone);
  359. if (typeof startDate === 'object')
  360. this.startDate = moment(startDate);
  361. if (!this.timePicker)
  362. this.startDate = this.startDate.startOf('day');
  363. this.oldStartDate = this.startDate.clone();
  364. this.updateView();
  365. this.updateCalendars();
  366. this.updateInputText();
  367. },
  368. setEndDate: function(endDate) {
  369. if (typeof endDate === 'string')
  370. this.endDate = moment(endDate, this.format).zone(this.timeZone);
  371. if (typeof endDate === 'object')
  372. this.endDate = moment(endDate);
  373. if (!this.timePicker)
  374. this.endDate = this.endDate.endOf('day');
  375. this.oldEndDate = this.endDate.clone();
  376. this.updateView();
  377. this.updateCalendars();
  378. this.updateInputText();
  379. },
  380. updateView: function () {
  381. this.leftCalendar.month.month(this.startDate.month()).year(this.startDate.year()).hour(this.startDate.hour()).minute(this.startDate.minute());
  382. this.rightCalendar.month.month(this.endDate.month()).year(this.endDate.year()).hour(this.endDate.hour()).minute(this.endDate.minute());
  383. this.updateFormInputs();
  384. },
  385. updateFormInputs: function () {
  386. this.container.find('input[name=daterangepicker_start]').val(this.startDate.format(this.format));
  387. this.container.find('input[name=daterangepicker_end]').val(this.endDate.format(this.format));
  388. if (this.startDate.isSame(this.endDate) || this.startDate.isBefore(this.endDate)) {
  389. this.container.find('button.applyBtn').removeAttr('disabled');
  390. } else {
  391. this.container.find('button.applyBtn').attr('disabled', 'disabled');
  392. }
  393. },
  394. updateFromControl: function () {
  395. if (!this.element.is('input')) return;
  396. if (!this.element.val().length) return;
  397. var dateString = this.element.val().split(this.separator),
  398. start = null,
  399. end = null;
  400. if(dateString.length === 2) {
  401. start = moment(dateString[0], this.format).zone(this.timeZone);
  402. end = moment(dateString[1], this.format).zone(this.timeZone);
  403. }
  404. if (this.singleDatePicker || start === null || end === null) {
  405. start = moment(this.element.val(), this.format).zone(this.timeZone);
  406. end = start;
  407. }
  408. if (end.isBefore(start)) return;
  409. this.oldStartDate = this.startDate.clone();
  410. this.oldEndDate = this.endDate.clone();
  411. this.startDate = start;
  412. this.endDate = end;
  413. if (!this.startDate.isSame(this.oldStartDate) || !this.endDate.isSame(this.oldEndDate))
  414. this.notify();
  415. this.updateCalendars();
  416. },
  417. notify: function () {
  418. this.updateView();
  419. this.cb(this.startDate, this.endDate, this.chosenLabel);
  420. },
  421. move: function () {
  422. var parentOffset = { top: 0, left: 0 };
  423. var parentRightEdge = $(window).width();
  424. if (!this.parentEl.is('body')) {
  425. parentOffset = {
  426. top: this.parentEl.offset().top - this.parentEl.scrollTop(),
  427. left: this.parentEl.offset().left - this.parentEl.scrollLeft()
  428. };
  429. parentRightEdge = this.parentEl[0].clientWidth + this.parentEl.offset().left;
  430. }
  431. if (this.opens == 'left') {
  432. this.container.css({
  433. top: this.element.offset().top + this.element.outerHeight() - parentOffset.top,
  434. right: parentRightEdge - this.element.offset().left - this.element.outerWidth(),
  435. left: 'auto'
  436. });
  437. if (this.container.offset().left < 0) {
  438. this.container.css({
  439. right: 'auto',
  440. left: 9
  441. });
  442. }
  443. } else if (this.opens == 'center') {
  444. this.container.css({
  445. top: this.element.offset().top + this.element.outerHeight() - parentOffset.top,
  446. left: this.element.offset().left - parentOffset.left + this.element.outerWidth() / 2
  447. - this.container.outerWidth() / 2,
  448. right: 'auto'
  449. });
  450. if (this.container.offset().left < 0) {
  451. this.container.css({
  452. right: 'auto',
  453. left: 9
  454. });
  455. }
  456. } else {
  457. this.container.css({
  458. top: this.element.offset().top + this.element.outerHeight() - parentOffset.top,
  459. left: this.element.offset().left - parentOffset.left,
  460. right: 'auto'
  461. });
  462. if (this.container.offset().left + this.container.outerWidth() > $(window).width()) {
  463. this.container.css({
  464. left: 'auto',
  465. right: 0
  466. });
  467. }
  468. }
  469. },
  470. toggle: function (e) {
  471. if (this.element.hasClass('active')) {
  472. this.hide();
  473. } else {
  474. this.show();
  475. }
  476. },
  477. show: function (e) {
  478. if (this.isShowing) return;
  479. this.element.addClass('active');
  480. this.container.show();
  481. this.move();
  482. // Create a click proxy that is private to this instance of datepicker, for unbinding
  483. this._outsideClickProxy = $.proxy(function (e) { this.outsideClick(e); }, this);
  484. // Bind global datepicker mousedown for hiding and
  485. $(document)
  486. .on('mousedown.daterangepicker', this._outsideClickProxy)
  487. // also support mobile devices
  488. .on('touchend.daterangepicker', this._outsideClickProxy)
  489. // also explicitly play nice with Bootstrap dropdowns, which stopPropagation when clicking them
  490. .on('click.daterangepicker', '[data-toggle=dropdown]', this._outsideClickProxy)
  491. // and also close when focus changes to outside the picker (eg. tabbing between controls)
  492. .on('focusin.daterangepicker', this._outsideClickProxy);
  493. this.isShowing = true;
  494. this.element.trigger('show.daterangepicker', this);
  495. },
  496. outsideClick: function (e) {
  497. var target = $(e.target);
  498. // if the page is clicked anywhere except within the daterangerpicker/button
  499. // itself then call this.hide()
  500. if (
  501. // ie modal dialog fix
  502. e.type == "focusin" ||
  503. target.closest(this.element).length ||
  504. target.closest(this.container).length ||
  505. target.closest('.calendar-date').length
  506. ) return;
  507. this.hide();
  508. },
  509. hide: function (e) {
  510. if (!this.isShowing) return;
  511. $(document)
  512. .off('.daterangepicker');
  513. this.element.removeClass('active');
  514. this.container.hide();
  515. if (!this.startDate.isSame(this.oldStartDate) || !this.endDate.isSame(this.oldEndDate))
  516. this.notify();
  517. this.oldStartDate = this.startDate.clone();
  518. this.oldEndDate = this.endDate.clone();
  519. this.isShowing = false;
  520. this.element.trigger('hide.daterangepicker', this);
  521. },
  522. enterRange: function (e) {
  523. // mouse pointer has entered a range label
  524. var label = e.target.innerHTML;
  525. if (label == this.locale.customRangeLabel) {
  526. this.updateView();
  527. } else {
  528. var dates = this.ranges[label];
  529. this.container.find('input[name=daterangepicker_start]').val(dates[0].format(this.format));
  530. this.container.find('input[name=daterangepicker_end]').val(dates[1].format(this.format));
  531. }
  532. },
  533. showCalendars: function() {
  534. this.container.addClass('show-calendar');
  535. this.move();
  536. this.element.trigger('showCalendar.daterangepicker', this);
  537. },
  538. hideCalendars: function() {
  539. this.container.removeClass('show-calendar');
  540. this.element.trigger('hideCalendar.daterangepicker', this);
  541. },
  542. // when a date is typed into the start to end date textboxes
  543. inputsChanged: function (e) {
  544. var el = $(e.target);
  545. var date = moment(el.val(), this.format);
  546. if (!date.isValid()) return;
  547. var startDate, endDate;
  548. if (el.attr('name') === 'daterangepicker_start') {
  549. startDate = date;
  550. endDate = this.endDate;
  551. } else {
  552. startDate = this.startDate;
  553. endDate = date;
  554. }
  555. this.setCustomDates(startDate, endDate);
  556. },
  557. inputsKeydown: function(e) {
  558. if (e.keyCode === 13) {
  559. this.inputsChanged(e);
  560. this.notify();
  561. }
  562. },
  563. updateInputText: function() {
  564. if (this.element.is('input') && !this.singleDatePicker) {
  565. this.element.val(this.startDate.format(this.format) + this.separator + this.endDate.format(this.format));
  566. } else if (this.element.is('input')) {
  567. this.element.val(this.endDate.format(this.format));
  568. }
  569. },
  570. clickRange: function (e) {
  571. var label = e.target.innerHTML;
  572. this.chosenLabel = label;
  573. if (label == this.locale.customRangeLabel) {
  574. this.showCalendars();
  575. } else {
  576. var dates = this.ranges[label];
  577. this.startDate = dates[0];
  578. this.endDate = dates[1];
  579. if (!this.timePicker) {
  580. this.startDate.startOf('day');
  581. this.endDate.endOf('day');
  582. }
  583. this.leftCalendar.month.month(this.startDate.month()).year(this.startDate.year()).hour(this.startDate.hour()).minute(this.startDate.minute());
  584. this.rightCalendar.month.month(this.endDate.month()).year(this.endDate.year()).hour(this.endDate.hour()).minute(this.endDate.minute());
  585. this.updateCalendars();
  586. this.updateInputText();
  587. this.hideCalendars();
  588. this.hide();
  589. this.element.trigger('apply.daterangepicker', this);
  590. }
  591. },
  592. clickPrev: function (e) {
  593. var cal = $(e.target).parents('.calendar');
  594. if (cal.hasClass('left')) {
  595. this.leftCalendar.month.subtract(1, 'month');
  596. } else {
  597. this.rightCalendar.month.subtract(1, 'month');
  598. }
  599. this.updateCalendars();
  600. },
  601. clickNext: function (e) {
  602. var cal = $(e.target).parents('.calendar');
  603. if (cal.hasClass('left')) {
  604. this.leftCalendar.month.add(1, 'month');
  605. } else {
  606. this.rightCalendar.month.add(1, 'month');
  607. }
  608. this.updateCalendars();
  609. },
  610. hoverDate: function (e) {
  611. var title = $(e.target).attr('data-title');
  612. var row = title.substr(1, 1);
  613. var col = title.substr(3, 1);
  614. var cal = $(e.target).parents('.calendar');
  615. if (cal.hasClass('left')) {
  616. this.container.find('input[name=daterangepicker_start]').val(this.leftCalendar.calendar[row][col].format(this.format));
  617. } else {
  618. this.container.find('input[name=daterangepicker_end]').val(this.rightCalendar.calendar[row][col].format(this.format));
  619. }
  620. },
  621. setCustomDates: function(startDate, endDate) {
  622. this.chosenLabel = this.locale.customRangeLabel;
  623. if (startDate.isAfter(endDate)) {
  624. var difference = this.endDate.diff(this.startDate);
  625. endDate = moment(startDate).add(difference, 'ms');
  626. }
  627. this.startDate = startDate;
  628. this.endDate = endDate;
  629. this.updateView();
  630. this.updateCalendars();
  631. },
  632. clickDate: function (e) {
  633. var title = $(e.target).attr('data-title');
  634. var row = title.substr(1, 1);
  635. var col = title.substr(3, 1);
  636. var cal = $(e.target).parents('.calendar');
  637. var startDate, endDate;
  638. if (cal.hasClass('left')) {
  639. startDate = this.leftCalendar.calendar[row][col];
  640. endDate = this.endDate;
  641. if (typeof this.dateLimit === 'object') {
  642. var maxDate = moment(startDate).add(this.dateLimit).startOf('day');
  643. if (endDate.isAfter(maxDate)) {
  644. endDate = maxDate;
  645. }
  646. }
  647. } else {
  648. startDate = this.startDate;
  649. endDate = this.rightCalendar.calendar[row][col];
  650. if (typeof this.dateLimit === 'object') {
  651. var minDate = moment(endDate).subtract(this.dateLimit).startOf('day');
  652. if (startDate.isBefore(minDate)) {
  653. startDate = minDate;
  654. }
  655. }
  656. }
  657. if (this.singleDatePicker && cal.hasClass('left')) {
  658. endDate = startDate.clone();
  659. } else if (this.singleDatePicker && cal.hasClass('right')) {
  660. startDate = endDate.clone();
  661. }
  662. cal.find('td').removeClass('active');
  663. $(e.target).addClass('active');
  664. this.setCustomDates(startDate, endDate);
  665. if (!this.timePicker)
  666. endDate.endOf('day');
  667. if (this.singleDatePicker && !this.timePicker)
  668. this.clickApply();
  669. },
  670. clickApply: function (e) {
  671. this.updateInputText();
  672. this.hide();
  673. this.element.trigger('apply.daterangepicker', this);
  674. },
  675. clickCancel: function (e) {
  676. this.startDate = this.oldStartDate;
  677. this.endDate = this.oldEndDate;
  678. this.chosenLabel = this.oldChosenLabel;
  679. this.updateView();
  680. this.updateCalendars();
  681. this.hide();
  682. this.element.trigger('cancel.daterangepicker', this);
  683. },
  684. updateMonthYear: function (e) {
  685. var isLeft = $(e.target).closest('.calendar').hasClass('left'),
  686. leftOrRight = isLeft ? 'left' : 'right',
  687. cal = this.container.find('.calendar.'+leftOrRight);
  688. // Month must be Number for new moment versions
  689. var month = parseInt(cal.find('.monthselect').val(), 10);
  690. var year = cal.find('.yearselect').val();
  691. this[leftOrRight+'Calendar'].month.month(month).year(year);
  692. this.updateCalendars();
  693. },
  694. updateTime: function(e) {
  695. var cal = $(e.target).closest('.calendar'),
  696. isLeft = cal.hasClass('left');
  697. var hour = parseInt(cal.find('.hourselect').val(), 10);
  698. var minute = parseInt(cal.find('.minuteselect').val(), 10);
  699. var second = 0;
  700. if (this.timePickerSeconds) {
  701. second = parseInt(cal.find('.secondselect').val(), 10);
  702. }
  703. if (this.timePicker12Hour) {
  704. var ampm = cal.find('.ampmselect').val();
  705. if (ampm === 'PM' && hour < 12)
  706. hour += 12;
  707. if (ampm === 'AM' && hour === 12)
  708. hour = 0;
  709. }
  710. if (isLeft) {
  711. var start = this.startDate.clone();
  712. start.hour(hour);
  713. start.minute(minute);
  714. start.second(second);
  715. this.startDate = start;
  716. this.leftCalendar.month.hour(hour).minute(minute).second(second);
  717. if (this.singleDatePicker)
  718. this.endDate = start.clone();
  719. } else {
  720. var end = this.endDate.clone();
  721. end.hour(hour);
  722. end.minute(minute);
  723. end.second(second);
  724. this.endDate = end;
  725. if (this.singleDatePicker)
  726. this.startDate = end.clone();
  727. this.rightCalendar.month.hour(hour).minute(minute).second(second);
  728. }
  729. this.updateView();
  730. this.updateCalendars();
  731. },
  732. updateCalendars: function () {
  733. this.leftCalendar.calendar = this.buildCalendar(this.leftCalendar.month.month(), this.leftCalendar.month.year(), this.leftCalendar.month.hour(), this.leftCalendar.month.minute(), this.leftCalendar.month.second(), 'left');
  734. this.rightCalendar.calendar = this.buildCalendar(this.rightCalendar.month.month(), this.rightCalendar.month.year(), this.rightCalendar.month.hour(), this.rightCalendar.month.minute(), this.rightCalendar.month.second(), 'right');
  735. this.container.find('.calendar.left').empty().html(this.renderCalendar(this.leftCalendar.calendar, this.startDate, this.minDate, this.maxDate, 'left'));
  736. this.container.find('.calendar.right').empty().html(this.renderCalendar(this.rightCalendar.calendar, this.endDate, this.singleDatePicker ? this.minDate : this.startDate, this.maxDate, 'right'));
  737. this.container.find('.ranges li').removeClass('active');
  738. var customRange = true;
  739. var i = 0;
  740. for (var range in this.ranges) {
  741. if (this.timePicker) {
  742. if (this.startDate.isSame(this.ranges[range][0]) && this.endDate.isSame(this.ranges[range][1])) {
  743. customRange = false;
  744. this.chosenLabel = this.container.find('.ranges li:eq(' + i + ')')
  745. .addClass('active').html();
  746. }
  747. } else {
  748. //ignore times when comparing dates if time picker is not enabled
  749. 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')) {
  750. customRange = false;
  751. this.chosenLabel = this.container.find('.ranges li:eq(' + i + ')')
  752. .addClass('active').html();
  753. }
  754. }
  755. i++;
  756. }
  757. if (customRange) {
  758. this.chosenLabel = this.container.find('.ranges li:last').addClass('active').html();
  759. this.showCalendars();
  760. }
  761. },
  762. buildCalendar: function (month, year, hour, minute, second, side) {
  763. var daysInMonth = moment([year, month]).daysInMonth();
  764. var firstDay = moment([year, month, 1]);
  765. var lastDay = moment([year, month, daysInMonth]);
  766. var lastMonth = moment(firstDay).subtract(1, 'month').month();
  767. var lastYear = moment(firstDay).subtract(1, 'month').year();
  768. var daysInLastMonth = moment([lastYear, lastMonth]).daysInMonth();
  769. var dayOfWeek = firstDay.day();
  770. var i;
  771. //initialize a 6 rows x 7 columns array for the calendar
  772. var calendar = [];
  773. calendar.firstDay = firstDay;
  774. calendar.lastDay = lastDay;
  775. for (i = 0; i < 6; i++) {
  776. calendar[i] = [];
  777. }
  778. //populate the calendar with date objects
  779. var startDay = daysInLastMonth - dayOfWeek + this.locale.firstDay + 1;
  780. if (startDay > daysInLastMonth)
  781. startDay -= 7;
  782. if (dayOfWeek == this.locale.firstDay)
  783. startDay = daysInLastMonth - 6;
  784. var curDate = moment([lastYear, lastMonth, startDay, 12, minute, second]).zone(this.timeZone);
  785. var col, row;
  786. for (i = 0, col = 0, row = 0; i < 42; i++, col++, curDate = moment(curDate).add(24, 'hour')) {
  787. if (i > 0 && col % 7 === 0) {
  788. col = 0;
  789. row++;
  790. }
  791. calendar[row][col] = curDate.clone().hour(hour);
  792. curDate.hour(12);
  793. if (this.minDate && calendar[row][col].format('YYYY-MM-DD') == this.minDate.format('YYYY-MM-DD') && calendar[row][col].isBefore(this.minDate) && side == 'left') {
  794. calendar[row][col] = this.minDate.clone();
  795. }
  796. if (this.maxDate && calendar[row][col].format('YYYY-MM-DD') == this.maxDate.format('YYYY-MM-DD') && calendar[row][col].isAfter(this.maxDate) && side == 'right') {
  797. calendar[row][col] = this.maxDate.clone();
  798. }
  799. }
  800. return calendar;
  801. },
  802. renderDropdowns: function (selected, minDate, maxDate) {
  803. var currentMonth = selected.month();
  804. var currentYear = selected.year();
  805. var maxYear = (maxDate && maxDate.year()) || (currentYear + 5);
  806. var minYear = (minDate && minDate.year()) || (currentYear - 50);
  807. var monthHtml = '<select class="monthselect">';
  808. var inMinYear = currentYear == minYear;
  809. var inMaxYear = currentYear == maxYear;
  810. for (var m = 0; m < 12; m++) {
  811. if ((!inMinYear || m >= minDate.month()) && (!inMaxYear || m <= maxDate.month())) {
  812. monthHtml += "<option value='" + m + "'" +
  813. (m === currentMonth ? " selected='selected'" : "") +
  814. ">" + this.locale.monthNames[m] + "</option>";
  815. }
  816. }
  817. monthHtml += "</select>";
  818. var yearHtml = '<select class="yearselect">';
  819. for (var y = minYear; y <= maxYear; y++) {
  820. yearHtml += '<option value="' + y + '"' +
  821. (y === currentYear ? ' selected="selected"' : '') +
  822. '>' + y + '</option>';
  823. }
  824. yearHtml += '</select>';
  825. return monthHtml + yearHtml;
  826. },
  827. renderCalendar: function (calendar, selected, minDate, maxDate, side) {
  828. var html = '<div class="calendar-date">';
  829. html += '<table class="table-condensed">';
  830. html += '<thead>';
  831. html += '<tr>';
  832. // add empty cell for week number
  833. if (this.showWeekNumbers)
  834. html += '<th></th>';
  835. if (!minDate || minDate.isBefore(calendar.firstDay)) {
  836. html += '<th class="prev available"><i class="fa fa-arrow-left icon-arrow-left glyphicon glyphicon-arrow-left"></i></th>';
  837. } else {
  838. html += '<th></th>';
  839. }
  840. var dateHtml = this.locale.monthNames[calendar[1][1].month()] + calendar[1][1].format(" YYYY");
  841. if (this.showDropdowns) {
  842. dateHtml = this.renderDropdowns(calendar[1][1], minDate, maxDate);
  843. }
  844. html += '<th colspan="5" class="month">' + dateHtml + '</th>';
  845. if (!maxDate || maxDate.isAfter(calendar.lastDay)) {
  846. html += '<th class="next available"><i class="fa fa-arrow-right icon-arrow-right glyphicon glyphicon-arrow-right"></i></th>';
  847. } else {
  848. html += '<th></th>';
  849. }
  850. html += '</tr>';
  851. html += '<tr>';
  852. // add week number label
  853. if (this.showWeekNumbers)
  854. html += '<th class="week">' + this.locale.weekLabel + '</th>';
  855. $.each(this.locale.daysOfWeek, function (index, dayOfWeek) {
  856. html += '<th>' + dayOfWeek + '</th>';
  857. });
  858. html += '</tr>';
  859. html += '</thead>';
  860. html += '<tbody>';
  861. for (var row = 0; row < 6; row++) {
  862. html += '<tr>';
  863. // add week number
  864. if (this.showWeekNumbers)
  865. html += '<td class="week">' + calendar[row][0].week() + '</td>';
  866. for (var col = 0; col < 7; col++) {
  867. var cname = 'available ';
  868. cname += (calendar[row][col].month() == calendar[1][1].month()) ? '' : 'off';
  869. if ((minDate && calendar[row][col].isBefore(minDate, 'day')) || (maxDate && calendar[row][col].isAfter(maxDate, 'day'))) {
  870. cname = ' off disabled ';
  871. } else if (calendar[row][col].format('YYYY-MM-DD') == selected.format('YYYY-MM-DD')) {
  872. cname += ' active ';
  873. if (calendar[row][col].format('YYYY-MM-DD') == this.startDate.format('YYYY-MM-DD')) {
  874. cname += ' start-date ';
  875. }
  876. if (calendar[row][col].format('YYYY-MM-DD') == this.endDate.format('YYYY-MM-DD')) {
  877. cname += ' end-date ';
  878. }
  879. } else if (calendar[row][col] >= this.startDate && calendar[row][col] <= this.endDate) {
  880. cname += ' in-range ';
  881. if (calendar[row][col].isSame(this.startDate)) { cname += ' start-date '; }
  882. if (calendar[row][col].isSame(this.endDate)) { cname += ' end-date '; }
  883. }
  884. var title = 'r' + row + 'c' + col;
  885. html += '<td class="' + cname.replace(/\s+/g, ' ').replace(/^\s?(.*?)\s?$/, '$1') + '" data-title="' + title + '">' + calendar[row][col].date() + '</td>';
  886. }
  887. html += '</tr>';
  888. }
  889. html += '</tbody>';
  890. html += '</table>';
  891. html += '</div>';
  892. var i;
  893. if (this.timePicker) {
  894. html += '<div class="calendar-time">';
  895. html += '<select class="hourselect">';
  896. // Disallow selections before the minDate or after the maxDate
  897. var min_hour = 0;
  898. var max_hour = 23;
  899. if (minDate && (side == 'left' || this.singleDatePicker) && selected.format('YYYY-MM-DD') == minDate.format('YYYY-MM-DD')) {
  900. min_hour = minDate.hour();
  901. if (selected.hour() < min_hour)
  902. selected.hour(min_hour);
  903. if (this.timePicker12Hour && min_hour >= 12 && selected.hour() >= 12)
  904. min_hour -= 12;
  905. if (this.timePicker12Hour && min_hour == 12)
  906. min_hour = 1;
  907. }
  908. if (maxDate && (side == 'right' || this.singleDatePicker) && selected.format('YYYY-MM-DD') == maxDate.format('YYYY-MM-DD')) {
  909. max_hour = maxDate.hour();
  910. if (selected.hour() > max_hour)
  911. selected.hour(max_hour);
  912. if (this.timePicker12Hour && max_hour >= 12 && selected.hour() >= 12)
  913. max_hour -= 12;
  914. }
  915. var start = 0;
  916. var end = 23;
  917. var selected_hour = selected.hour();
  918. if (this.timePicker12Hour) {
  919. start = 1;
  920. end = 12;
  921. if (selected_hour >= 12)
  922. selected_hour -= 12;
  923. if (selected_hour === 0)
  924. selected_hour = 12;
  925. }
  926. for (i = start; i <= end; i++) {
  927. if (i == selected_hour) {
  928. html += '<option value="' + i + '" selected="selected">' + i + '</option>';
  929. } else if (i < min_hour || i > max_hour) {
  930. html += '<option value="' + i + '" disabled="disabled" class="disabled">' + i + '</option>';
  931. } else {
  932. html += '<option value="' + i + '">' + i + '</option>';
  933. }
  934. }
  935. html += '</select> : ';
  936. html += '<select class="minuteselect">';
  937. // Disallow selections before the minDate or after the maxDate
  938. var min_minute = 0;
  939. var max_minute = 59;
  940. if (minDate && (side == 'left' || this.singleDatePicker) && selected.format('YYYY-MM-DD h A') == minDate.format('YYYY-MM-DD h A')) {
  941. min_minute = minDate.minute();
  942. if (selected.minute() < min_minute)
  943. selected.minute(min_minute);
  944. }
  945. if (maxDate && (side == 'right' || this.singleDatePicker) && selected.format('YYYY-MM-DD h A') == maxDate.format('YYYY-MM-DD h A')) {
  946. max_minute = maxDate.minute();
  947. if (selected.minute() > max_minute)
  948. selected.minute(max_minute);
  949. }
  950. for (i = 0; i < 60; i += this.timePickerIncrement) {
  951. var num = i;
  952. if (num < 10)
  953. num = '0' + num;
  954. if (i == selected.minute()) {
  955. html += '<option value="' + i + '" selected="selected">' + num + '</option>';
  956. } else if (i < min_minute || i > max_minute) {
  957. html += '<option value="' + i + '" disabled="disabled" class="disabled">' + num + '</option>';
  958. } else {
  959. html += '<option value="' + i + '">' + num + '</option>';
  960. }
  961. }
  962. html += '</select> ';
  963. if (this.timePickerSeconds) {
  964. html += ': <select class="secondselect">';
  965. for (i = 0; i < 60; i += this.timePickerIncrement) {
  966. var num = i;
  967. if (num < 10)
  968. num = '0' + num;
  969. if (i == selected.second()) {
  970. html += '<option value="' + i + '" selected="selected">' + num + '</option>';
  971. } else {
  972. html += '<option value="' + i + '">' + num + '</option>';
  973. }
  974. }
  975. html += '</select>';
  976. }
  977. if (this.timePicker12Hour) {
  978. html += '<select class="ampmselect">';
  979. // Disallow selection before the minDate or after the maxDate
  980. var am_html = '';
  981. var pm_html = '';
  982. if (minDate && (side == 'left' || this.singleDatePicker) && selected.format('YYYY-MM-DD') == minDate.format('YYYY-MM-DD') && minDate.hour() >= 12) {
  983. am_html = ' disabled="disabled" class="disabled"';
  984. }
  985. if (maxDate && (side == 'right' || this.singleDatePicker) && selected.format('YYYY-MM-DD') == maxDate.format('YYYY-MM-DD') && maxDate.hour() < 12) {
  986. pm_html = ' disabled="disabled" class="disabled"';
  987. }
  988. if (selected.hour() >= 12) {
  989. html += '<option value="AM"' + am_html + '>AM</option><option value="PM" selected="selected"' + pm_html + '>PM</option>';
  990. } else {
  991. html += '<option value="AM" selected="selected"' + am_html + '>AM</option><option value="PM"' + pm_html + '>PM</option>';
  992. }
  993. html += '</select>';
  994. }
  995. html += '</div>';
  996. }
  997. return html;
  998. },
  999. remove: function() {
  1000. this.container.remove();
  1001. this.element.off('.daterangepicker');
  1002. this.element.removeData('daterangepicker');
  1003. }
  1004. };
  1005. $.fn.daterangepicker = function (options, cb) {
  1006. this.each(function () {
  1007. var el = $(this);
  1008. if (el.data('daterangepicker'))
  1009. el.data('daterangepicker').remove();
  1010. el.data('daterangepicker', new DateRangePicker(el, options, cb));
  1011. });
  1012. return this;
  1013. };
  1014. }));