Native HTML 5 datepickers are great, they offer a simple to use interface (that works particularly well on mobile) plus they’re dead simple, just stick a [type=date] attribute on a <input> element and away you go. However, not all browsers support this so and will simply fall back to [type=text] so a fallback is required for unsupported browsers

Enter Modernizr

Modernizr is a Javascript library that contains a collection of tests – or “detects” that tells you what HTML, CSS and JavaScript features the user’s browser has to offer. Feature dection using Modernizr looks something like this:

if (Modernizr.awesomeNewFeature) {
  doSupportedStuff();
} else {
  doFallback();
}

Detecting Support for Native Datepickers

Applying this to our datepicker, we can detect support for <input type="date"> with a statement like this:

if (Modernizr.inputtypes.date) {
  /* Yeah, datepickers all round! */
} else {
  /* Doh, no datepickers this time! */
}

Providing a Fallback

If the feature is unsupported we can apply the jQuery UI to any <input> elements with a type="date" attribute.

if (!Modernizr.inputtypes.date) {
  /* apply datepicker ui to selected element */
  $('input[type=date]').datepicker({
    /* Keep the date consistent */
    dateFormat: 'yy-mm-dd'
  });
}

Note the reversal of logic here using the ! operator, this just simplifies our code as we don’t need to do anything if does support the date feature. The dateFormat: 'yy-mm-dd' just keeps the date format consistent between the jQuery UI datepicker and the native one.

Gettin’ Fancy

The example above assumes that you’ll have already pulled in the jQuery UI library and css, but if you’re only using those for this particular fallback you could end up adding a lot of weight for users even if their browser does support the date feature. Well we can choose to only include those assets if the user needs them using Modernizr too!

if (!Modernizr.inputtypes.date) {
    /* get jQuery-ui css */
    $('', {
      rel: 'stylesheet',
      type: 'text/css',
      href: 'https://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css'
    }).appendTo('head');
    /* get jQuery-ui */
    jQuery.getScript('https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js')
    /* wait till it's loaded */
    .done(function() {
      /* apply datepicker ui to selected element */
      $('input[type=date]').datepicker({
      /* Keep the date consistent */
      dateFormat: 'yy-mm-dd'
    });
  });
}

The order here is important and the use of the .done() method, we need to make sure the assets are loaded before applying the the jQuery UI datepicker, or we’re gonna have a bad time!

See the Pen Input Date with Modernizr Fallback by Josh (@iamjoshellis) on CodePen.