Creating mobile Web applications with HTML 5, Part 5: Develop new visual UI features in HTML 5

Add Canvas, CSS3, and more semantic elements to mobile Web apps

HTML 5 comes with plenty of new features for mobile Web applications, including visual ones that usually make the most impact. Canvas is the most eye-catching of the new UI capabilities, providing full 2-D graphics in the browser. In this article you learn to use Canvas as well as some of the other new visual elements in HTML 5 that are more subtle but make a big difference for mobile users.

Share:

Michael Galpin, Software architect, eBay

Michael Galpin's photoMichael Galpin is an architect at eBay. He is a frequent contributor to developerWorks. He has spoken at various technical conferences, including JavaOne, EclipseCon, and AjaxWorld. To get a preview of what he is working on next, follow @michaelg on Twitter.



29 June 2010

Also available in Chinese Russian Japanese Vietnamese

About this series

HTML 5 is a very hyped technology, but with good reason. It promises to be a technological tipping point to bring desktop application capabilities to the browser. As promising as it is for traditional browsers, it has even more potential for mobile browsers. Even better, the most popular mobile browsers have already adopted and implemented many significant parts of the HTML 5 specification. In this five-part series, you will take a closer look at several of those new technologies that are part of HTML 5 and can have a huge impact on mobile Web application development. In each part, you will develop a working mobile Web application showcasing an HTML 5 feature that you can use on modern mobile Web browsers, like the ones found on the iPhone and Android-based devices.


Prerequisites

In this article, you will develop Web applications using the latest Web technologies. Most of the code here is just HTML, JavaScript, and CSS—the core technologies of any Web developer. The most important thing you will need are browsers to test things on. Most of the code in this article will run on the latest desktop browsers with some noted exceptions. Of course, you must test on mobile browsers too, and you will want the latest iPhone and Android SDKs for those. In this article, iPhone SDK 3.1.3 and Android SDK 2.1 were used. See Resources for links.


Getting graphical with Canvas

Frequently used acronyms

  • Ajax: Asynchronous JavaScript + XML
  • API: Application Programming Interface
  • CSS: Cascading stylesheet
  • DOM: Document Object Model
  • HTML: Hypertext Markup Language
  • SDK: Software Developer Kit
  • UI: User Interface
  • XML: Extensible Markup Language

For years, Web developers have complained about Canvas. Now why would anyone complain about a native drawing API in the browser? After all, it lets you create the kind of graphical interfaces that otherwise require some kind of browser plugin (and as every mobile Web developer knows, plugins are often not available on the most popular mobile browsers.) The reason that Web developers have complained about Canvas is that, while it has been available on Firefox and Safari for many years now, it has never been supported in the most popular desktop browser, Microsoft®Internet Explorer®. Even the early versions of Internet Explorer 9 do not support Canvas. So for years, Canvas has been the ultimate technology tease. You can find these amazing Canvas samples all over the Internet, but you cannot use it for most Web applications because Internet Explorer lacked support for it. Luckily for mobile Web developers, Canvas has no such limitations. All of the Webkit-based browsers that you target can implement Canvas and heavily optimize its performance.

The Canvas API is a low level API for drawing. It lets you create lines, curves, polygons, and circles and fill them in with colors, gradients, and so on. You can create text and you can perform numerous types of geometric transformations to anything on the Canvas. As you can imagine, such an API has countless uses. Take a look at an application that creates a graphical report using Canvas. Figure 1 shows a screen capture of the application, a bar graph of yearly results.

Figure 1. Canvas based reports application running on the Android browser
Screen capture of a Canvas-based reports app running on the Android browser

What you see in Figure 1 is not a static image in the browser. The report graphic is generated on the fly using the Canvas API. Listing 1 shows the HTML that creates this report.

Listing 1. Report HTML
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width; initial-scale=1.0; 
        maximum-scale=1.0; user-scalable=0;"/>
    <meta name="apple-touch-fullscreen" content="YES" />
    <title>HTML 5 Reports</title>
    <script type="text/javascript">
        function init(){
            var data = [{year : "2007",sales : 49},
                {year : "2008",sales : 131},
                {year : "2009",sales : 294}, 
                {year : "2010",sales : 405}];
            var report = {x : "year",
                    y : "sales",
                    values : data};
            graph(report, 350, 300);
        }
    </script>
</head>
<body onload="init()">
    <canvas id="graph"></canvas>
</body>
</html>

This shows the basic HTML structure. The body of the document has a single canvas tag. In the init function, called when the body of the document is loaded, you define static data (the report data) and pass it to the graph function. While you defined the report as static data here, it is easy to imagine this being dynamically downloaded over the network using Ajax. The report function contains all of the interesting code, so let's take a look at it in Listing 2.

Listing 2. The graph function
function graph(report, maxWidth, maxHeight){
    var data = report.values;
    var canvas = document.getElementById("graph");
    var axisBuffer = 20;
    canvas.height = maxHeight + 100;
    canvas.width = maxWidth;
    var ctx = canvas.getContext("2d");

    var width = 50;
    var buffer = 20;
    var i = 0;
    var x = buffer + axisBuffer;
    ctx.font = "bold 12px sans-serif";
    ctx.textAlign = "start";
    for (i=0;i<data.length;i++){
        ctx.fillStyle = "rgba(0, 0, 200, 0.9)";
        ctx.fillRect(x, maxHeight - (data[i][report.y] / 2), 
                 width, (data[i][report.y] / 2));
        ctx.fillStyle = "rgba(0, 0, 0, 0.9)";
        ctx.fillText(data[i][report.x], x + (width / 4), maxHeight + 15);
        x += width + buffer;
    }

    // draw the horizontal axis
    ctx.moveTo(axisBuffer, maxHeight);
    ctx.lineTo(axisBuffer+maxWidth, maxHeight);
    ctx.strokeStyle = "black";
    ctx.stroke();

    // draw the vertical axis
    ctx.moveTo(axisBuffer,0);
    ctx.lineTo(axisBuffer,maxHeight);
    ctx.stroke();

    // draw gridlines
    var lineSpacing = 50;
    var numLines = maxHeight/lineSpacing;
    var y = lineSpacing;
    ctx.font = "10px sans-serif";
    ctx.textBaseline = "middle";
    for (i=0;i<numLines;i++){
        ctx.strokeStyle = "rgba(0,0,0,0.25)";
        ctx.moveTo(axisBuffer, y);
        ctx.lineTo(axisBuffer + maxWidth,y);
        ctx.stroke();
        ctx.fillStyle = "rgba(0,0,0, 0.75)";
        ctx.fillText(""+(2*(maxHeight -y)), 0, y);
        y += lineSpacing; 
    }
}

In the first section of this function, you set up objects needed to create the report, like the width and height of the canvas, and padding variables. You also create the canvas context object, as this is the object you use to do all of the actual drawing. Then you draw the bar graphs seen in Figure 1, by iterating over the report data. First, you set the fillStyle property. This can be as simple as setting a color, like you might do to use CSS. In this case, use the rgba notation to set not just the color, but also the alpha value. (This is the transparency of the color, and you will see this again later when I discuss CSS 3.0 features in HTML 5.) After setting the fillStyle property, you create the bar graph for the data point using the fillRect API. Here, you specify the (x,y) starting point of the rectangle and its height and width. Next, you redefine the fillStyle because you want to print some text as part of the report. You use the fillText API to draw text on the canvas. This API takes the (x,y) starting point and the text. You do this for each of the data points, creating a bar graph with a label below it for each.

Next, you need to draw the other parts of the graph—the axes and grid lines. First, you draw the horizontal and vertical axes. For each of these, use the moveTo API to set the point from which you will begin to draw a line. Then use the lineTo API to draw a line from the start point to the end point passed in to the lineTo call. Note that this does not actually draw a line; instead, you call the stroke API to draw the line. After drawing both axes, you draw the gridlines along with their labels by evenly spacing them and then drawing the lines using the same combination of moveTo, lineTo, and stroke.

This is all of the code you need to programmatically create the report graphics. You have seen many of the most important and most commonly used canvas APIs in this example, but there are several other APIs (such as for drawing curves). You can do some pretty amazing things with these APIs, and you can do them on any of the Webkit-based browsers out there. If graphics are not your thing, HTML 5 still has a lot of new eye candy for you in the form of Cascading Style Sheets (CSS) 3.0.


The wonderful world of CSS3

When you say HTML 5, you might instantly think of HTML tags. Of course, HTML 5 definitely includes new tags, and you will take a look at some of those in the next section. In the previous section, you saw how to use a <canvas> tag to create a canvas object inside the DOM. However, the majority of the code was JavaScript. HTML is just part of the story of HTML 5—JavaScript and CSS are equally important parts of it. Many of the new user interface elements in HTML 5 are provided by the latest revision of the CSS standard, CSS 3.0. In Figure 2, a Web page using several new CSS 3.0 techniques appears on an Android-based phone and on the iPhone.

Figure 2. New CSS capabilities of mobile devices
Screen capture comparison of new CSS capabilities on Android and iPhone mobile devices

Figure 2 shows many new CSS features on both an Android-based device and iPhone. The image on the left is from an Android-based device. The reason it is bigger is that it is from a Motorola Droid, which has a higher resolution screen than the iPhone 3GS used for the image on the right. Hence, you also see more of the page on the Droid. However, you might see that the "The Gettysburg Address" heading has a reflection that fades away on the iPhone but does not fade away and winds up obscuring the next heading on the Droid. This is just a gentle reminder that even though both Android-based devices and the iPhone have Webkit-based browsers, there are subtle differences between them, and you must be diligent in your testing. Now look at the code (in Listing 3) that generated this beautiful page, starting with the top of the page .

Listing 3. Code for the top half of the page
<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        function $(id){
            return document.getElementById(id);
        }
        function init(){
            var i=0;
            var row = {};
            var cell = {};
            var topics = ["nth-child", "gradients", "alpha", "text effects", 
                          "reflections", "transformations"];
            for (i=0;i<topics.length;i++){
                row = document.createElement("tr");
                cell = document.createElement("td");
                cell.appendChild(document.createTextNode(topics[i]));
                row.appendChild(cell);
                $("dtable").appendChild(row);
            }
        }
    </script>
    <style type="text/css">
        header > h1{
            color: yellow;
            background: -webkit-gradient(linear, left top, left bottom, 
                             from(blue), to(white))
        }
        tr:nth-child(4n+1) { color: navy; }
        tr:nth-child(4n+2) { color: green; }
        tr:nth-child(4n+3) { color: maroon; }
        tr:nth-child(4n+4) { color: purple; }

        input[type="text"]{
            background: rgba(150, 30, 30, 0.5);
        }
    </style>
</head>
<body onload="init()">
    <header>
        <h1>The World of CSS3</h1>
        <div>What kind of CSS3 does your browser support?</div>
    </header>
    <table id="dtable"></table>
    <div id="formSection">
        <label for="name">What's your name?</label>
        <input type="text" id="name"></input>
        <button id="rtBtn" onclick="rotate()">Rotate</button>
    </div>
</body>
</html>

The code in Listing 3 draws all of the UI above the "Gettysburg Address" heading. You will look at the code for the bottom part of the page shortly.

The first thing you will look at is the header on the page. If you look at the body of the HTML page near the bottom of the listing, you see that this header is literally in a header tag—one of the new HTML elements in HTML 5.

Now look at the style element (above the HTML body in Listing 3). The text is styled using CSS with the selector header > h1. This rule makes the text yellow, but it also gives it a blue and white background. This background has a gradient applied to it. This is the first example you'll see of CSS features that are prefixed with -webkit. As you might guess, this makes this CSS proprietary to Webkit-based browsers. However, in most cases, these are part of the CSS 3.0 standard, but they fall into areas where the standard is still slightly in flux. In most cases, both Webkit browsers and Mozilla Firefox based browsers have implemented these features. If you need to also target Mozilla browsers (like the mobile version of Firefox, called Fennec, which is rapidly gaining popularity on Nokia smartphones in Europe), then you can usually change the -webkit prefix to -moz.

The next thing you do is display a list of topics using the table called dtable. As you can see in Figure 2, the color changes from line to line as you display the contents of this table. You do this using the next section of CSS, the tr:nth-child declarations. You can use the nth-child declaration on any repeating element. You pass a formula used as a predicate to see if it is a valid rule for the element. In this case, you state that row numbers of the form 4n+1 (1, 5, 9, and so on) are colored navy, row numbers of the form 4n+2 (2, 6, 10, and so on) are colored green, and then, similarly, maroon and purple. There's a good chance that you have had to implement similar visual treatments to tables, lists, and other things in the past, but usually through tedious JavaScript.

The last visual elements are the red-colored text field with the label What's your name? and a button that says Rotate. The red coloring of the text field is accomplished using a type-specific input selector. In other words, this is a CSS rule that will only apply to input elements whose type is text. Now you might be wondering what the Rotate button does. You can see from the code in Listing 4 that it calls a function called rotate.

Listing 4. JavaScript rotation function using CSS
function rotate(){
    $("formSection").style["-webkit-transform"] = "rotateZ(-5deg)";
    $("formSection").style["-webkit-transition"] = 
          "-webkit-transform 2s ease-in-out";
    $("rtBtn").innerHTML = "Undo";
    $("rtBtn").onclick = function() {
        $("formSection").style["-webkit-transform"] = "";
        $("rtBtn").innerHTML = "Rotate";
        $("rtBtn").setAttribute("onclick", "rotate()");
    }
}

This rotation function uses JavaScript to change the CSS that is applied to the div called formSection. (Note: you are using $() as an alias for document.getElementById().) To rotate the div, you set its -webkit-transform style to rotateZ(-5deg), thus rotating it five degrees counterclockwise. Next, you set the -webkit-transform style to -webkit-transform 2s ease-in-out. This makes the rotation take two seconds, starting out slowly, accelerating, and then slowing down again at the end. In Figure 3, the left side shows the initial, unrotated position of the What's your name? field. The right side shows the visual effect of the partially rotated field and it's Undo button.

Figure 3. Rotating HTML elements
Screen capture of rotating HTML elements on a mobile device

See the link in Resources to see this effect in action on an HTML 5 compliant browser such as Chrome, Safari 4, and Opera.

Now let's move on to the bottom half of the page in Figure 2. Here you see several interesting examples of image and text effects, as well as layouts. The code for this is in Listing 5.

Listing 5. Code for bottom half of Figure 2
<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        h2 {
            -webkit-text-fill-color: blue;
            -webkit-text-stroke-color: yellow;
            -webkit-text-stroke-width: 1.5px;
            background: -webkit-gradient(radial, 430 50, 0, 430 50, 200, from(red), 
to(#000));
            -webkit-box-reflect:below 5px -webkit-gradient(linear, left top, left 
bottom, from(transparent), color-stop(0.5, transparent), to(white));
        }
        h3{
            color: rgba(0,0,255,0.75);
            background: rgba(255,255,0,0.5);
        }
        .xyz{
            text-shadow: #6374AB 4px -4px 2px;
            white-space: nowrap;
            width: 14em; 
            height: 2em; 
            overflow: hidden;
            text-overflow: ellipsis; 
            border: 1px solid #bbb; 
            border-radius: 9px;             
            background-color: #fff;
        }
        .abc {
            border: 1px solid #000;
            border-radius: 9px;        
            -webkit-column-count:4;
            -webkit-column-rule: 1px solid #a00;
            -webkit-column-gap: 0.75em;
        }
    </style>
</head>
<body onload="init()">
    <h2>The Gettysburg Address</h2>
    <h3>Abraham Lincoln, Gettysburg, PA. November 19, 1863</h3>
    <div class="xyz">
        Four score and seven years ago our fathers brought forth on this 
        continent a new nation, conceived in liberty, and dedicated to 
            the proposition that all men are created equal.
    </div>
    <div class="abc">
        Now we are engaged in a great civil war, testing whether that 
            nation, or any nation, so conceived and so dedicated, can long 
            endure. We are met on a great battle-field of that war. We have 
            come to dedicate a portion of that field, as a final resting 
            place for those who here gave their lives that that nation might 
            live. It is altogether fitting and proper that we should do this.
    </div>
</body>
</html>

Let's go element by element through this code. First, you create a heading for "The Gettysburg Address" and style this in a number of ways.

  1. You use -webkit-text-fill-color, -webkit-text-stroke-color, and -webkit-text-stroke-width styles to create the blue-inside-the-yellow effect.
  2. A red and black background is placed behind the text by setting the background style -webkit-gradient. Note that this is a radial gradient, whereas earlier you saw a linear gradient. Both work equally well on smartphones.
  3. You apply a reflection to the heading by setting the -webkit-box-reflect style. This style is set to reflect the heading five pixels below it, with a gradient effect applied to the reflection. The gradient effect here makes the reflection seem to fade away. If you go back to Figure 2, you'll see that it's this combination of applying a gradient to a reflection that the Android browser doesn't do: it just renders the reflection without any gradient.

Moving on to the next heading, you apply a very simple styling to it. It just has a color for the text, and a separate color for the background. Both of these colors use the rgba function to specify the red-green-blue values, plus an alpha transparency value. A value of 1.0 is completely opaque and a value of 0.0 is transparent.

Next up in Listing 5 is the code for the first paragraph of the passage. This text has a border around it and you use the new border-radius style to achieve rounded corners. You see these kinds of corners used all over the Web today, and they are usually accomplished using images. That seems downright primitive in comparison to how easily they are done with CSS 3.0. You apply a shadow to the text of the paragraph by using the text-shadow style. Finally, notice that the area for the paragraph is constrained by setting the height and width of the parent div, and that the text is too big. Instead of just cutting the text off like you would see in older browsers, you get a nice ellipsis (...) effect by setting the text-overflow style.

Finally, you come to the last section of text. It also has a border around it, but notice that it appears in four columns with column separators. To do this, set the -webkit-column-count style, and sett the accompanying -webkit-column-rule style to get the separators. You can only imagine how tedious it is to get the text to format like this without these new CSS 3.0 features. This can also be a useful feature when you create simple headers and footers, both of which are new elements in HTML 5. Take a look at them and some of the other new markup introduced by HTML 5.


New semantics

HTML 5 adds many new elements to the HTML markup soup. Some of these elements will cause browsers to provide new rendering treatments. Others will add extra features that then become available through JavaScript. However, some of them will do neither. They will look the same and have the same programmatic interfaces as <span>, <div>, and <p>. However, they will add extra semantic meaning. These new semantics are important for non-visual users of the page (including anyone using assistive technologies like screen readers) but also for computer programs like search engine crawlers. These new tags also provide hooks for developers to write more expressive CSS selectors . Figure 4 shows a web page using some of the new semantic elements.

Figure 4. New HTML 5 elements on the iPhone
Screen capture of new HTML 5 header, nav, article, and section, and aside elements on the iPhone

This example in Figure 4 has a header element, as well as nav elements, an article, a section, and an aside. These elements do not cause any special rendering. They just add semantic value, and you can use them to write CSS that gives them visual treatments to match that semantic value. The code for the page shown in Figure 4 is in Listing 6.

Listing 6. New semantic elements in HTML 5
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width; initial-scale=1.0; 
        maximum-scale=1.0; user-scalable=0;"/>
    <meta name="apple-touch-fullscreen" content="YES" />
<title>Get the latest markup</title>
</head>
<body>
    <header style="border: 1px dotted #000;border-radius: 3px;">
        <hgroup align="center">
            <h1>Real documents have headers</h1>
            <h2>Even if they don't say so</h2>
        </hgroup>
        <hgroup>
        <nav style="-webkit-column-count:3;-webkit-column-rule: 1px solid #a00;">
            <a href="new-css.html">CSS3</a><br/>
            <a href="report.html">Canvas</a><br/>
            <a href="elements.html">Markup</a>
        </nav>
        </hgroup>
    </header>
    <article>
       <h1>There are a lot of new markup elements in HTML5</h1>
       <time datetime="2010-05-16" pubdate>Sunday, May 16</time>
       <section>Did you notice that we just had two H1's? 
       But it's cool!</section>
       <aside style="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;" >
            If this page was really popular, I'd put an ad here and make some
            serious cash
        </aside>
    </article>
</body>
</html>

You can see a number of the new elements mentioned previously. Notice that you also applied some of the new CSS styles to create a box with roundedcorners around the header and to create separators for the nav. You also used the text overflow styling on the aside. The point here is that you can create much more meaningful markup with no extra work, and then you can make it appear as if you had used <div> and <span>. To see an example of new HTML 5 elements that have more visual and programming impact, look at Figure 5. (View a text-only version of Figure 5.)

Figure 5. Forms created with HTML 5 on the iPhone
Screen capture of several forms created with HTML 5 from elements on the iPhone

The screen in Figure 5 uses many new form elements available in HTML 5. In many cases, these look like existing elements, but you can expect browsers to add better visual representations of these richer form elements. To get a glimpse, look at the above in the Opera desktop browser in Figure 6. (View a text-only version of Figure 6.)

Figure 6. HTML 5 form elements on Opera
Screen capture of several forms created with HTML 5 form elements on Opera

Opera has been a leader in implementing HTML 5 features, and this is especially true for the new form elements. Now look at the code that produced Listing 4 and Listing 5 so that you can better understand why Opera rendered things the way it did. Listing 7 shows this code.

Listing 7. HTML 5 form elements in code
<form id="settings">
<fieldset id="inputs" style="border: 1px solid #000;border-radius: 6px;">
    <legend>Settings</legend>
    <label for="name">Username</label>
    <input id="name" name="name" type="text" required autofocus /><br/>
    <label for="name">Name</label>
    <input id="name" name="name" type="text" 
          placeholder="First and last name" required /><br/>
    <label for="email">Email</label>
    <input id="email" name="email" type="email"           
           placeholder="example@domain.com" required /><br/>
    <label for="phone">Phone</label>
    <input id="phone" name="phone" type="tel" 
          placeholder="Eg. +447500000000" required /><br/>
    <label for="dob">Date of birth</label>
    <input id="dob" name="dob" type="date" required/>
    <fieldset style="border: 1px dotted #000; border-radius: 6px">
        <legend>Preferred Contact Method</legend>
        <ol>
            <li>
                <input id="emailMeth" name="contactMethod" 
                            type="radio">
                <label for="emailMeth">Email</label>
            </li>
            <li>
                <input id="phoneMeth" name="contactMethod" 
                            type="radio">
                <label for="phoneMeth">Phone</label>
            </li>
        </ol>
    </fieldset>
    <label for="climate">Preferred external temperature</label>
    <input id="climate" name="climate" type="range" min="50" 
          max="100" step="5" value="70"/><br/>
    <label for="color">Favorite color</label>
    <input id="color" name="color" type="color"/><br/>
    <label for="referrer">Where'd you hear about us?</label>
    <input type="url" name="refUrl" id="referrer" list="urls"/>
    <datalist id="urls">
        <option label="TechCrunch" value="http://www.techcrunch.com/">
        <option label="ReadWrite Web" value="http://www.readwriteweb.com/">
        <option label="Engadget" value="http://www.engadget.com/">
        <option label="Ajaxian" value="http://www.ajaxian.com/">
    </datalist><br/>
    <button type="button" onclick="checkInputs()">Save</button>
</fieldset>
</form>

The form elements in Listing 7 show many of the new features of HTML 5. Notice two of the new attributes, required and autofocus. The required attribute is used during form validation (more on that below) and the autofocus attribute lets you pick the element on the page too get focus. Also notice that several of the elements have placeholder text. This is a pattern that many websites have used for years—put some example or explanatory text inside the text box—but the developer always had to hack the code. You can see how nicely the iPhone implements this in Figure 4.

Next you get to see some of the new types allowed for input elements, like email, phone, date, range, color, and url. These all get rendered as text fields on the iPhone and Android browsers today, but that is what they would look like if they were created using less semantically correct HTML 4.0. In Figure 5, you can see what they might look like in the future. The date input has to gain focus before it shows off its new UI (a pop-up calendar) on Opera. This is also true for the url input in Figure 7, but that's not because it is url input. That's because it has a list attribute. This points to the datalist element which contains the allowed values for that field. When you focus on the field, you get to see the possible values (in this case, several URLs) from the datalist, similar to Ajax style auto-suggest fields that are popular. You can see both the date and the datalist features in Figure 7.

Figure 7. HTML 5 input with dates and datalists
Screen capture of HTML 5 input with dates and datalists

You can expect that many of the input types will allow for more useful visual representations as Webkit continues to rapidly evolve. Opera gives you a good look at the future. Many of these input fields also provide validation, and HTML 5 has a whole set of new validation APIs. These features do not yet work on the iPhone or on Android-based devices, but they do work in their desktop equivalents, so you can expect them to shop on the mobile browsers soon. Take a look at using the new validation APIs in Listing 8.

Listing 8. HTML 5 Validation APIs in action
function checkInputs(){
    var inputs = document.getElementById("inputs").childNodes;
    var len = inputs.length;
    var i = 0;
    var input = null;
    var errors = [];
    for (i=0;i<len;i++){
        input = inputs.item(i);
        if (input.nodeName == "INPUT"){
            if (input.validity){
                if (!input.checkValidity()){
                    errors.push(input.validationMessage);
                }
            }
        }
    }
    var errMsg = "There are " + errors.length + " errors";
    var notify = function(){
        var notification = 
            webkitNotifications.createNotification(null, "Errors!", errMsg);
        notification.show();
    };
    if (window.webkitNotifications){
        if (webkitNotifications.checkPermission()){
            webkitNotifications.requestPermission(notify);
        } else {
            notify();
        }
    } else {
        alert(errMsg);
    }
}

Each of the input elements has a validity property. You can use this or you can also use the checkValidity() function that returns true or false, and the validationMessage property to get a localized error message. At the time of this writing, the most recent desktop browsers do not return anything consistent or standard for validationMessage, so it is of limited use. The validity object can be used to check for different types of errors, like valueMissing, rangeOverflow, rangeUnderflow, patternMismatch, and tooLong. For example, if the element has a required attribute but the user leaves it blank, then validity.valueMissing will be true.

Finally, notice in Listing 8 that after you figure out all of the validation errors, you then try to use webkitNotifications. These are like system notifications on your desktop computer, and they are available in the latest version of Chrome. So you can once again hope that they will come soon to the iPhone and Android browsers. Using the API is straightforward. The only tricky part is that you need to check whether the user gave your site permission to use this API. If not, you must request permission, passing in the function that you want to be invoked if the user gives permission.


Summary

In this article, you took a whirlwind tour of many of the new UI-related features in HTML 5, from new elements to new style to the drawing canvas. These features (with the exception for a few notable exceptions at the end) are all available for you to use on the Webkit-based browsers found on the iPhone and on Android-based devices. Other popular platforms like the Blackberry and Nokia smartphones are getting more powerful browsers that also leverage the same technologies you have looked at in this article. As a mobile Web developer you have the opportunity to target a wide range of users with visual features more powerful than anything you have ever had access to with HTML, CSS, and JavaScript on desktop browsers. In the previous four parts of this series, you learned about many other new technologies (like geolocation and Web Workers) that are available to you on these amazing new mobile browsers. The mobile Web is not some weaker version of the Web you have programmed for years. It is a more powerful version full of possibilities.


Download

DescriptionNameSize
Article source codeui.zip5KB

Resources

Learn

Get products and technologies

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into XML on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=XML, Open source, Web development, Mobile development
ArticleID=497633
ArticleTitle=Creating mobile Web applications with HTML 5, Part 5: Develop new visual UI features in HTML 5
publish-date=06292010