HTML5 and CSS3, Second Edition

(singke) #1
technique we used is brittle. It targets a specific set of browsers and works
only for the color control. Thankfully, there’s a better solution.

Detecting Features with Modernizr
The Modernizr library can detect support for many HTML5 and CSS3 features.^3
It doesn’t add the missing functionality, but it does provide several mecha-
nisms similar to the solution we implemented for detecting things that are
more bulletproof than solutions we might roll ourselves.

We load Modernizr in the <head> of our document after our CSS references.
Modernizr makes a Modernizr object available to us, which we can use to detect
features and load fallbacks. For example, here’s how we do our color-picker
fallback with Modernizr:

if(Modernizr.inputtypes.color){
// we havecolorsupport
}else{
// we don'thavecolorsupport.
}

However, we need to load additional libraries when we don’t have support.
We can use Modernizr’s load() method to detect a feature and load other scripts,
then execute our own code when the code loads. Here’s how we do it:

html5_forms/modernizr/javascripts/fallbacks.js
varapplyColorPicker=function(){
$('input[type=color]').simpleColor();
};

Modernizr.load(
{
test:Modernizr.inputtypes.color,
nope:"javascripts/jquery.simple-color.js",
callback:function(url,result){
if(!result){
applyColorPicker();
}
}
}
);

The load() method can take a JavaScript object that defines a specific feature
test and what should happen when the feature exists or is missing. We use
yep to load scripts when the feature is supported, and nope to load scripts
when the feature is missing. We can also define a callback function that runs


  1. http://www.modernizr.com/


report erratum • discuss

Describing Data with New Input Fields • 47


Download from Wow! eBook <www.wowebook.com>

Free download pdf