Categories:
Partners

Implementing a cross browser HTML5 pop up calendar control

HTML5's <input type="date" /> element (and its variants such as "datetime") is a great time saver when you need to add date related controls to your forms. However, until all the major browsers support these new elements, you still have to supply an alternate solution for the other browsers. Putting theory into practice now, lets create a sample form that uses HTML5's date control where it's supported, and fall back to jQuery UI's Date Picker widget where it's not:

Click on the text field below:

Date of birth:

Here's the code for it:

<head>
<script type="text/javascript">
	var datefield=document.createElement("input")
	datefield.setAttribute("type", "date")
	if (datefield.type!="date"){ //if browser doesn't support input type="date", load files for jQuery UI Date Picker
		document.write('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />\n')
		document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"><\/script>\n')
		document.write('<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"><\/script>\n') 
	}
</script>

<script>
if (datefield.type!="date"){ //if browser doesn't support input type="date", initialize date picker widget:
	jQuery(function($){ //on document.ready
		$('#birthday').datepicker();
	})
}
</script>
</head>

<body>
<form>
<b>Date of birth:</b>
<input type="date" id="birthday" name="birthday" size="20" />
<input type="button" value="Submit" name="B1"></p>
</form>
</body>

In browsers that support HTML5's <input type="date" /> element, a native calendar will pop up, while in other browsers, a custom jQuery date picker instead. To maximize the benefits to the former group, we only load the .js files associated with the custom jQuery Date Picker in those browsers that do not support HTML5's intrinsic calendar control. A nice compromise in a currently uncompromising browser landscape.

Copyright 1997-2014 JavaScript Kit. NO PART may be reproduced without author's permission.