HTML 5 Feature Detection Using Modernizr

HTML 5 is probably the most exciting improvement to come to the web, since the popularization of AJAX. However, as shown by last weeks article (HTML 5 Forms), only the most cutting edge browsers support many of the new HTML 5 features. To progressively enhance a site for HTML 5 enabled browsers, developers need a way to detect if the browser supports a desired HTML 5 feature. Enter Modernizr by Faruk Ates and Paul Irish.

How to do it…

Some examples of available HTML 5 feature detection:

if (Modernizr.canvas) {
	// canvas feature
}
else {
	// fallback
}

if (Modernizr.localstorage && Modernizr.sessionstorage) {
	// storage feature
}
else {
	// fallback
}

Some examples of available HTML 5 and CSS 3 feature detection:

if (! Modernizr.borderradius) {
	// borderradius fallback
}

if (! Modernizr.boxshadow) {
	// boxshadow fallback
}

Some examples of available HTML 5 input feature and attribute detection:

if (! Modernizr.inputtypes.email){
	// input type email fallback
}

if (! Modernizr.input.placeholder){
	// placeholder text fallback
}

All the above detections using the YUI 3 Gallery version of Modernizr:

YUI({
	modules: {
		fullpath: http://github.com/mattsnider/yui3-gallery/raw/master/build/gallery-modernizr/gallery-modernizr-min.js
	}
}).use(gallery-modernizr, function(Y) {
if (Y.Modernizr.canvas) {
	// canvas feature
}
else {
	// fallback
}

if (Y.Modernizr.localstorage && Y.Modernizr.sessionstorage) {
	// storage feature
}
else {
	// fallback
}

if (! Y.Modernizr.borderradius) {
	// borderradius fallback
}

if (! Y.Modernizr.boxshadow) {
	// boxshadow fallback
}

if (! Y.Modernizr.inputtypes.email){
	// input type email fallback
}

if (! Y.Modernizr.input.placeholder){
	// placeholder text fallback
}
}

How it works …

Modernizr uses a variety of techniques to detect if the current browsers supports a desired HTML 5 feature. This allows developers to build their sites for most browsers, but augment their sites for browsers that have specific HTML 5 features enabled. Best of all Modernizr is already included in the YUI 3 gallery (gallery-modernizr), although it is not up-to-date (version 1.2 of Modernizr). I have updated the code to version 1.6, but it isn&rsquot;t in the gallery CDN yet. Get the latest code from my yui3-gallery fork, at gallery-modernizr.