HTML5 and CSS3, Second Edition

(singke) #1
around. If it doesn’t, we can assume that the browser has implemented a
color picker because the input field isn’t acting like a text box.

Finally, we call this detection function. To avoid loading the plug-in when we
don’t need it, we use JavaScript to inject a new <script> tag, which loads the
plug-in and activates it when the script has loaded.

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

if(!hasColorSupport()){
varscript= document.createElement('script');
script.src="javascripts/jquery.simple-color.js";

if(script.readyState){ // IE support
script.onreadystatechange=function () {
if(this.readyState==='loaded'|| this.readyState==='complete'){
script.onreadystatechange= null;
applyColorPicker();
}
};
}else{
// Otherbrowsers
script.onload= applyColorPicker;
}

document.getElementsByTagName("head")[0].appendChild(script);
}

Internet Explorer requires us to use onreadystatechange and detect the value of
the readystate property. Other browsers simply let us attach a function name
to the onload event. By including both we ensure our fallback works across
the board.

Now things work fine in all browsers. We just need a little extra CSS to make
the color picker line up with the other columns:

html5_forms/stylesheets/style.css
.simpleColorContainer,.simpleColorDisplay{
float: left;
}

The process for creating fallbacks for other form fields is the same—we detect
whether the browser supports the control natively, and, if it doesn’t, we load
the necessary library and apply the JavaScript version instead. Eventually
you’ll be able to phase out the JavaScript controls and rely completely on the
controls in the browser. The solution we used works, but the detection

Chapter 3. Creating User-Friendly Web Forms • 46


Download from Wow! eBook <www.wowebook.com> report erratum • discuss

Free download pdf