Use HTML 5 datepickers instead of jQuery-UI

Did you know Modernizr will test for the existence of certain HTML 5 input elements? Since Google Chrome and most mobile browsers have a built-in datepicker for <input type="date"> elements, you can use yepnope (automatically provided as part of Modernizr) to dynamically load jQuery-UI (a relatively large file, even when only the datepicker code is included) only when needed.

HTML:

<input type="date" id="from_date" name="from_date">

JavaScript:

yepnope({ /* included with Modernizr */
  test : Modernizr.inputtypes.date,
  nope : {
    'css': '/path-to-your-css/jquery-ui-1.10.3.custom.min.css',
    'js': '/path-to-your-js/jquery-ui-1.10.3.datepicker.min.js'
  },
  callback: { // executed once files are loaded
    'js': function() { $('input[type=date]').datepicker({dateFormat: "yy-mm-dd"}); } // default HTML5 format
  }
});

 

See the Pen Use HTML 5 datepickers instead of jQuery-UI by Martin Blase (@mblase75) on CodePen.

3 Replies to “Use HTML 5 datepickers instead of jQuery-UI”

    • Either inside of a $(document).ready(function(){...}); block, or at the bottom of the page. Either way, you need to load jQuery and Modernizr before the above code runs.

      The HTML5Boilerplate approach, which I favor, is to load Modernizr in the <head>...</head> of the document, and then load jQuery followed by other code at the very bottom of the <body>, to eliminate the need for $(document).ready.

  1. Thanks – working fine. I had it pretty close to the way you suggested. Turns out I mistyped the name of the jqery-ui file – doh! This was a big help – thanks again.

Leave a Reply

Your email address will not be published. Required fields are marked *

*