date.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /**
  2. * @file
  3. * Polyfill for HTML5 date input.
  4. */
  5. (function ($, Modernizr, Drupal) {
  6. 'use strict';
  7. /**
  8. * Attach datepicker fallback on date elements.
  9. *
  10. * @type {Drupal~behavior}
  11. *
  12. * @prop {Drupal~behaviorAttach} attach
  13. * Attaches the behavior. Accepts in `settings.date` an object listing
  14. * elements to process, keyed by the HTML ID of the form element containing
  15. * the human-readable value. Each element is an datepicker settings object.
  16. * @prop {Drupal~behaviorDetach} detach
  17. * Detach the behavior destroying datepickers on effected elements.
  18. */
  19. Drupal.behaviors.date = {
  20. attach: function (context, settings) {
  21. var $context = $(context);
  22. // Skip if date are supported by the browser.
  23. if (Modernizr.inputtypes.date === true) {
  24. return;
  25. }
  26. $context.find('input[data-drupal-date-format]').once('datePicker').each(function () {
  27. var $input = $(this);
  28. var datepickerSettings = {};
  29. var dateFormat = $input.data('drupalDateFormat');
  30. // The date format is saved in PHP style, we need to convert to jQuery
  31. // datepicker.
  32. datepickerSettings.dateFormat = dateFormat
  33. .replace('Y', 'yy')
  34. .replace('m', 'mm')
  35. .replace('d', 'dd');
  36. // Add min and max date if set on the input.
  37. if ($input.attr('min')) {
  38. datepickerSettings.minDate = $input.attr('min');
  39. }
  40. if ($input.attr('max')) {
  41. datepickerSettings.maxDate = $input.attr('max');
  42. }
  43. $input.datepicker(datepickerSettings);
  44. });
  45. },
  46. detach: function (context, settings, trigger) {
  47. if (trigger === 'unload') {
  48. $(context).find('input[data-drupal-date-format]').findOnce('datePicker').datepicker('destroy');
  49. }
  50. }
  51. };
  52. })(jQuery, Modernizr, Drupal);