HTML5 and CSS3, Second Edition

(singke) #1
Typically, to use a plug-in like SimpleColor, we would download the plug-in,
attach it to our page with a <script> tag, and then attach the plug-in to the
element with a separate bit of JavaScript. But we want to use this color
picker plug-in only if the browser doesn’t support the control natively, so we’ll
use JavaScript to detect whether the browser supports input fields with a
type of color. If it doesn’t, then we’ll load the plug-in dynamically.

First, since we’re going to need jQuery, we’ll load that by placing it right above
the closing <body> tag:

html5_forms/index.html
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>

Then we create a new file called javascripts/fallbacks.js and link it to the bottom
of the HTML page with a <script> tag, like this:

html5_forms/index.html
<scriptsrc="javascripts/fallbacks.js"></script>

Then, in javascripts/fallbacks.js we create a function to detect color support in the
browser:

html5_forms/javascripts/fallbacks.js
Line 1 functionhasColorSupport(){


  • element= document.createElement("input");

  • element.setAttribute("type","color");

  • varhasColorType= (element.type==="color");
    5 // handlepartialimplementation

  • if(hasColorType){

  • vartestString="foo";

  • element.value= testString;

  • hasColorType= (element.value!= testString);
    10 }

  • return(hasColorType);

  • }


In this function we use JavaScript to create an element and set its type
attribute to color. Then we retrieve the type attribute to see whether the
browser allowed us to set the attribute. If it comes back with a value of color,
then we have support for that type.

Things get interesting on line 6. Some browsers have partially implemented
the color type. They support the field, but they don’t actually display a color
widget. We still end up with a text field on the page. So, in our detection
method, we set the value for our input field and see whether the value sticks

report erratum • discuss

Describing Data with New Input Fields • 45


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

Free download pdf