Creating mobile Web applications with HTML 5, Part 5: Develop

25
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 Skill Level: Intermediate Michael Galpin Software architect eBay 29 Jun 2010 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. About this series Other articles in this series Part 1: Combine HTML 5, geolocation APIs, and Web services to create mobile mashups Part 2: Unlock local storage for mobile Web apps with HTML 5 Part 3: Make mobile Web applications work offline with HTML 5 Part 4: Use Web Workers to speed up your mobile Web applications HTML 5 is a very hyped technology, but with good reason. It promises to be a Develop new visual UI features in HTML 5 Trademarks © Copyright IBM Corporation 2010. All rights reserved. Page 1 of 25

Transcript of Creating mobile Web applications with HTML 5, Part 5: Develop

Page 1: Creating mobile Web applications with HTML 5, Part 5: Develop

Creating mobile Web applications with HTML 5,Part 5: Develop new visual UI features in HTML 5Add Canvas, CSS3, and more semantic elements to mobileWeb apps

Skill Level: Intermediate

Michael GalpinSoftware architecteBay

29 Jun 2010

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

About this series

Other articles in this series

• Part 1: Combine HTML 5, geolocation APIs, and Webservices to create mobile mashups

• Part 2: Unlock local storage for mobile Web apps withHTML 5

• Part 3: Make mobile Web applications work offline withHTML 5

• Part 4: Use Web Workers to speed up your mobile Webapplications

HTML 5 is a very hyped technology, but with good reason. It promises to be a

Develop new visual UI features in HTML 5 Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 1 of 25

Page 2: Creating mobile Web applications with HTML 5, Part 5: Develop

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 mobilebrowsers. Even better, the most popular mobile browsers have already adopted andimplemented many significant parts of the HTML 5 specification. In this five-partseries, you will take a closer look at several of those new technologies that are partof HTML 5 and can have a huge impact on mobile Web application development. Ineach part, you will develop a working mobile Web application showcasing an HTML5 feature that you can use on modern mobile Web browsers, like the ones found onthe 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 ofany Web developer. The most important thing you will need are browsers to testthings on. Most of the code in this article will run on the latest desktop browsers withsome noted exceptions. Of course, you must test on mobile browsers too, and youwill want the latest iPhone and Android SDKs for those. In this article, iPhone SDK3.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 anyonecomplain about a native drawing API in the browser? After all, it lets you create thekind of graphical interfaces that otherwise require some kind of browser plugin (andas every mobile Web developer knows, plugins are often not available on the mostpopular mobile browsers.) The reason that Web developers have complained aboutCanvas 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

developerWorks® ibm.com/developerWorks

Develop new visual UI features in HTML 5 Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 2 of 25

Page 3: Creating mobile Web applications with HTML 5, Part 5: Develop

support Canvas. So for years, Canvas has been the ultimate technology tease. Youcan find these amazing Canvas samples all over the Internet, but you cannot use itfor most Web applications because Internet Explorer lacked support for it. Luckily formobile Web developers, Canvas has no such limitations. All of the Webkit-basedbrowsers that you target can implement Canvas and heavily optimize itsperformance.

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 cancreate text and you can perform numerous types of geometric transformations toanything on the Canvas. As you can imagine, such an API has countless uses. Takea look at an application that creates a graphical report using Canvas. Figure 1 showsa screen capture of the application, a bar graph of yearly results.

Figure 1. Canvas based reports application running on the Android browser

ibm.com/developerWorks developerWorks®

Develop new visual UI features in HTML 5 Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 3 of 25

Page 4: Creating mobile Web applications with HTML 5, Part 5: Develop

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

developerWorks® ibm.com/developerWorks

Develop new visual UI features in HTML 5 Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 4 of 25

Page 5: Creating mobile Web applications with HTML 5, Part 5: Develop

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 singlecanvas 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 youdefined the report as static data here, it is easy to imagine this being dynamicallydownloaded over the network using Ajax. The report function contains all of theinteresting 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

ibm.com/developerWorks developerWorks®

Develop new visual UI features in HTML 5 Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 5 of 25

Page 6: Creating mobile Web applications with HTML 5, Part 5: Develop

ctx.moveTo(axisBuffer, maxHeight);ctx.lineTo(axisBuffer+maxWidth, maxHeight);ctx.strokeStyle = "black";ctx.stroke();

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

// draw gridlinesvar 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 thecanvas 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, likeyou might do to use CSS. In this case, use the rgba notation to set not just thecolor, but also the alpha value. (This is the transparency of the color, and you willsee this again later when I discuss CSS 3.0 features in HTML 5.) After setting thefillStyle property, you create the bar graph for the data point using thefillRect API. Here, you specify the (x,y) starting point of the rectangle and itsheight and width. Next, you redefine the fillStyle because you want to printsome text as part of the report. You use the fillText API to draw text on thecanvas. This API takes the (x,y) starting point and the text. You do this for each ofthe 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 toset the point from which you will begin to draw a line. Then use the lineTo API todraw a line from the start point to the end point passed in to the lineTo call. Notethat this does not actually draw a line; instead, you call the stroke API to draw theline. After drawing both axes, you draw the gridlines along with their labels by evenlyspacing 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. Youhave seen many of the most important and most commonly used canvas APIs in thisexample, but there are several other APIs (such as for drawing curves). You can do

developerWorks® ibm.com/developerWorks

Develop new visual UI features in HTML 5 Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 6 of 25

Page 7: Creating mobile Web applications with HTML 5, Part 5: Develop

some pretty amazing things with these APIs, and you can do them on any of theWebkit-based browsers out there. If graphics are not your thing, HTML 5 still has alot 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 5definitely includes new tags, and you will take a look at some of those in the nextsection. In the previous section, you saw how to use a <canvas> tag to create acanvas 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 importantparts of it. Many of the new user interface elements in HTML 5 are provided by thelatest revision of the CSS standard, CSS 3.0. In Figure 2, a Web page using severalnew CSS 3.0 techniques appears on an Android-based phone and on the iPhone.

Figure 2. New CSS capabilities of mobile devices

ibm.com/developerWorks developerWorks®

Develop new visual UI features in HTML 5 Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 7 of 25

Page 8: Creating mobile Web applications with HTML 5, Part 5: Develop

Figure 2 shows many new CSS features on both an Android-based device andiPhone. The image on the left is from an Android-based device. The reason it isbigger is that it is from a Motorola Droid, which has a higher resolution screen thanthe iPhone 3GS used for the image on the right. Hence, you also see more of thepage 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 andwinds up obscuring the next heading on the Droid. This is just a gentle reminder thateven though both Android-based devices and the iPhone have Webkit-basedbrowsers, there are subtle differences between them, and you must be diligent inyour 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>

developerWorks® ibm.com/developerWorks

Develop new visual UI features in HTML 5 Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 8 of 25

Page 9: Creating mobile Web applications with HTML 5, Part 5: Develop

<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 ofthe HTML page near the bottom of the listing, you see that this header is literally in aheader 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 isstyled 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 gradientapplied 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

ibm.com/developerWorks developerWorks®

Develop new visual UI features in HTML 5 Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 9 of 25

Page 10: Creating mobile Web applications with HTML 5, Part 5: Develop

browsers. However, in most cases, these are part of the CSS 3.0 standard, but theyfall into areas where the standard is still slightly in flux. In most cases, both Webkitbrowsers and Mozilla Firefox based browsers have implemented these features. Ifyou need to also target Mozilla browsers (like the mobile version of Firefox, calledFennec, which is rapidly gaining popularity on Nokia smartphones in Europe), thenyou can usually change the -webkit prefix to -moz.

The next thing you do is display a list of topics using the table called dtable. Asyou can see in Figure 2, the color changes from line to line as you display thecontents of this table. You do this using the next section of CSS, thetr:nth-child declarations. You can use the nth-child declaration on anyrepeating element. You pass a formula used as a predicate to see if it is a valid rulefor 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) arecolored green, and then, similarly, maroon and purple. There's a good chance thatyou have had to implement similar visual treatments to tables, lists, and other thingsin the past, but usually through tedious JavaScript.

The last visual elements are the red-colored text field with the label What's yourname? and a button that says Rotate. The red coloring of the text field isaccomplished using a type-specific input selector. In other words, this is a CSS rulethat will only apply to input elements whose type is text. Now you might bewondering what the Rotate button does. You can see from the code in Listing 4 thatit 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 thediv called formSection. (Note: you are using $() as an alias fordocument.getElementById().) To rotate the div, you set its-webkit-transform style to rotateZ(-5deg), thus rotating it five degreescounterclockwise. Next, you set the -webkit-transform style to-webkit-transform 2s ease-in-out. This makes the rotation take twoseconds, 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 yourname? field. The right side shows the visual effect of the partially rotated field andit's Undo button.

developerWorks® ibm.com/developerWorks

Develop new visual UI features in HTML 5 Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 10 of 25

Page 11: Creating mobile Web applications with HTML 5, Part 5: Develop

Figure 3. Rotating HTML elements

See the link in Resources to see this effect in action on an HTML 5 compliantbrowser 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 severalinteresting examples of image and text effects, as well as layouts. The code for thisis 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;

ibm.com/developerWorks developerWorks®

Develop new visual UI features in HTML 5 Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 11 of 25

Page 12: Creating mobile Web applications with HTML 5, Part 5: Develop

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 thiscontinent 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 thatnation, or any nation, so conceived and so dedicated, can longendure. We are met on a great battle-field of that war. We havecome to dedicate a portion of that field, as a final restingplace for those who here gave their lives that that nation mightlive. 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 "TheGettysburg Address" and style this in a number of ways.

1. You use -webkit-text-fill-color,-webkit-text-stroke-color, and -webkit-text-stroke-widthstyles to create the blue-inside-the-yellow effect.

2. A red and black background is placed behind the text by setting thebackground style -webkit-gradient. Note that this is a radial gradient,whereas earlier you saw a linear gradient. Both work equally well onsmartphones.

3. You apply a reflection to the heading by setting the-webkit-box-reflect style. This style is set to reflect the heading fivepixels below it, with a gradient effect applied to the reflection. Thegradient effect here makes the reflection seem to fade away. If you goback to Figure 2, you'll see that it's this combination of applying a gradientto a reflection that the Android browser doesn't do: it just renders thereflection without any gradient.

Moving on to the next heading, you apply a very simple styling to it. It just has acolor for the text, and a separate color for the background. Both of these colors usethe rgba function to specify the red-green-blue values, plus an alpha transparencyvalue. 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 aborder around it and you use the new border-radius style to achieve rounded

developerWorks® ibm.com/developerWorks

Develop new visual UI features in HTML 5 Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 12 of 25

Page 13: Creating mobile Web applications with HTML 5, Part 5: Develop

corners. You see these kinds of corners used all over the Web today, and they areusually accomplished using images. That seems downright primitive in comparisonto how easily they are done with CSS 3.0. You apply a shadow to the text of theparagraph by using the text-shadow style. Finally, notice that the area for theparagraph is constrained by setting the height and width of the parent div, and thatthe text is too big. Instead of just cutting the text off like you would see in olderbrowsers, 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 noticethat 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 howtedious 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, bothof which are new elements in HTML 5. Take a look at them and some of the othernew markup introduced by HTML 5.

New semantics

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

Figure 4. New HTML 5 elements on the iPhone

ibm.com/developerWorks developerWorks®

Develop new visual UI features in HTML 5 Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 13 of 25

Page 14: Creating mobile Web applications with HTML 5, Part 5: Develop

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

Listing 6. New semantic elements in HTML 5

<!DOCTYPE html><html>

developerWorks® ibm.com/developerWorks

Develop new visual UI features in HTML 5 Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 14 of 25

Page 15: Creating mobile Web applications with HTML 5, Part 5: Develop

<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 someserious cash

</aside></article>

</body></html>

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

Figure 5. Forms created with HTML 5 on the iPhone

ibm.com/developerWorks developerWorks®

Develop new visual UI features in HTML 5 Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 15 of 25

Page 16: Creating mobile Web applications with HTML 5, Part 5: Develop

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

Figure 6. HTML 5 form elements on Opera

developerWorks® ibm.com/developerWorks

Develop new visual UI features in HTML 5 Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 16 of 25

Page 17: Creating mobile Web applications with HTML 5, Part 5: Develop

Opera has been a leader in implementing HTML 5 features, and this is especiallytrue for the new form elements. Now look at the code that produced Listing 4 andListing 5 so that you can better understand why Opera rendered things the way itdid. 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="[email protected]" 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>

ibm.com/developerWorks developerWorks®

Develop new visual UI features in HTML 5 Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 17 of 25

Page 18: Creating mobile Web applications with HTML 5, Part 5: Develop

<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. Noticetwo of the new attributes, required and autofocus. The required attribute isused during form validation (more on that below) and the autofocus attribute letsyou pick the element on the page too get focus. Also notice that several of theelements have placeholder text. This is a pattern that many websites have usedfor years—put some example or explanatory text inside the text box—but thedeveloper always had to hack the code. You can see how nicely the iPhoneimplements 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 onthe iPhone and Android browsers today, but that is what they would look like if theywere created using less semantically correct HTML 4.0. In Figure 5, you can seewhat they might look like in the future. The date input has to gain focus before itshows off its new UI (a pop-up calendar) on Opera. This is also true for the urlinput in Figure 7, but that's not because it is url input. That's because it has a listattribute. This points to the datalist element which contains the allowed values forthat field. When you focus on the field, you get to see the possible values (in thiscase, several URLs) from the datalist, similar to Ajax style auto-suggest fields thatare popular. You can see both the date and the datalist features in Figure 7.

Figure 7. HTML 5 input with dates and datalists

developerWorks® ibm.com/developerWorks

Develop new visual UI features in HTML 5 Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 18 of 25

Page 19: Creating mobile Web applications with HTML 5, Part 5: Develop

You can expect that many of the input types will allow for more useful visualrepresentations as Webkit continues to rapidly evolve. Opera gives you a good lookat the future. Many of these input fields also provide validation, and HTML 5 has awhole set of new validation APIs. These features do not yet work on the iPhone oron Android-based devices, but they do work in their desktop equivalents, so you canexpect them to shop on the mobile browsers soon. Take a look at using the newvalidation 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 canalso use the checkValidity() function that returns true or false, and the

ibm.com/developerWorks developerWorks®

Develop new visual UI features in HTML 5 Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 19 of 25

Page 20: Creating mobile Web applications with HTML 5, Part 5: Develop

validationMessage property to get a localized error message. At the time of thiswriting, the most recent desktop browsers do not return anything consistent orstandard for validationMessage, so it is of limited use. The validity object can beused to check for different types of errors, like valueMissing, rangeOverflow,rangeUnderflow, patternMismatch, and tooLong. For example, if the elementhas a required attribute but the user leaves it blank, thenvalidity.valueMissing will be true.

Finally, notice in Listing 8 that after you figure out all of the validation errors, youthen try to use webkitNotifications. These are like system notifications on yourdesktop computer, and they are available in the latest version of Chrome. So youcan 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 checkwhether the user gave your site permission to use this API. If not, you must requestpermission, passing in the function that you want to be invoked if the user givespermission.

Summary

Other articles in this series

• Part 1: Combine HTML 5, geolocation APIs, and Webservices to create mobile mashups

• Part 2: Unlock local storage for mobile Web apps withHTML 5

• Part 3: Make mobile Web applications work offline withHTML 5

• Part 4: Use Web Workers to speed up your mobile Webapplications

In this article, you took a whirlwind tour of many of the new UI-related features inHTML 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 youto use on the Webkit-based browsers found on the iPhone and on Android-baseddevices. Other popular platforms like the Blackberry and Nokia smartphones aregetting more powerful browsers that also leverage the same technologies you havelooked at in this article. As a mobile Web developer you have the opportunity totarget a wide range of users with visual features more powerful than anything youhave ever had access to with HTML, CSS, and JavaScript on desktop browsers. Inthe previous four parts of this series, you learned about many other newtechnologies (like geolocation and Web Workers) that are available to you on theseamazing new mobile browsers. The mobile Web is not some weaker version of theWeb you have programmed for years. It is a more powerful version full ofpossibilities.

developerWorks® ibm.com/developerWorks

Develop new visual UI features in HTML 5 Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 20 of 25

Page 21: Creating mobile Web applications with HTML 5, Part 5: Develop

ibm.com/developerWorks developerWorks®

Develop new visual UI features in HTML 5 Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 21 of 25

Page 22: Creating mobile Web applications with HTML 5, Part 5: Develop

Downloads

Description Name Size Downloadmethod

Article source code ui.zip 5KB HTTP

Information about download methods

developerWorks® ibm.com/developerWorks

Develop new visual UI features in HTML 5 Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 22 of 25

Page 23: Creating mobile Web applications with HTML 5, Part 5: Develop

Resources

Learn

• Creating mobile Web applications with HTML 5, Part 1: Combine HTML 5,geolocation APIs, and Web services to create mobile mashups (Michael Galpin,developerWorks, May 2010): Find and track location coordinates to use invarious Web services. Use the various aspects of the geolocation standard withHTML 5 and popular Web services to create an interesting mobile mashup inPart 1 of this series.

• Creating mobile Web applications with HTML 5, Part 2: Unlock local storage formobile Web applications with HTML 5 (Michael Galpin, developerWorks, May2010): Explore an important new feature in HTML 5 for wireless applications.With the standardization of local storage and a simple API, store large amountsof data on the client and improve performance.

• Creating mobile Web applications with HTML 5, Part 3: Make mobile Webapplications work offline with HTML 5 (Michael Galpin, developerWorks, June2010): Enable your application to function with or without an Internet connectionand learn to detect when your application goes from offline to online and viceversa.

• Creating mobile Web applications with HTML 5, Part 4: Use Web Workers tospeed up your mobile Web applications (Michael Galpin, developerWorks, June2010): Web Workers bring multi-threading to Web applications. Learn to workwith Web Workers and which tasks are most appropriate for them.

• New elements in HTML 5 (Elliotte Rusty Harold, developerWorks, August2007): HTML 5 is not just about JavaScript. Read about some of the newmarkup in HTML 5.

• Create modern Web sites using HTML5 and CSS3 (Joe Lennon,developerWorks,, March 2010): Many modern desktop browsers also havesome of these same features. Learn about them in this tutorial.

• The future of HTML, Part 1: WHATWG (Ed Dumbill, developerWorks,December 2005): Find out more about canvas in this article.

• See the rotate function in action in an HTML 5 compliant browser.

• Android and iPhone browser wars, Part 1: WebKit to the rescue (Frank Ableson,developerWorks, December 2009): Do you like the mobile Web applicationapproach using HTML 5 approach, but still want your application in the iPhoneApp Store and Android Market? See how you can get the best of both worlds inPart 1 of this two-part article series.

• Create Ajax applications for the mobile Web (Michael Galpin, developerWorks,March 2010): Explore how to use Ajax, a key part of any mobile Web

ibm.com/developerWorks developerWorks®

Develop new visual UI features in HTML 5 Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 23 of 25

Page 24: Creating mobile Web applications with HTML 5, Part 5: Develop

application.

• Dive Into HTML 5: Check out this free book for a great look at HTML 5 detectiontechniques as well as the many features of HTML 5.

• Safari Reference Library: Keep this resource handy if you develop Webapplications for the iPhone.

• W3C HTML 5 Specification (Working Draft, March 2010): Explore this definitivesource on HTML 5.

• More articles by this author (Michael Galpin, developerWorks, April2006-current): Read articles about XML, Eclipse, Apache Geronimo, Ajax, moreGoogle APIs, and other technologies.

• My developerWorks: Personalize your developerWorks experience.

• IBM XML certification: Find out how you can become an IBM-CertifiedDeveloper in XML and related technologies.

• XML technical library: See the developerWorks XML Zone for a wide range oftechnical articles and tips, tutorials, standards, and IBM Redbooks.

• developerWorks technical events and webcasts: Stay current with technology inthese sessions.

• developerWorks on Twitter: Join today to follow developerWorks tweets.

• developerWorks podcasts: Listen to interesting interviews and discussions forsoftware developers.

Get products and technologies

• Modernizr project is a comprehensive utility for detecting HTML 5 features.

• The Android Developers Web site: Download the Android SDK, access the APIreference, and get the latest news on Android.

• iPhone SDK: Get the latest iPhone SDK to develop iPad, iPhone and iPodtouch applications.

• The Android Open Source Project: Get the open source code for the Androidmobile platform.

• The Google App Engine SDK: Download Java™ and Python tools to buildscalable Web applications using Google.

• IBM product evaluation versions: Download or explore the online trials in theIBM SOA Sandbox and get your hands on application development tools andmiddleware products from DB2®, Lotus®, Rational®, Tivoli®, andWebSphere®.

Discuss

developerWorks® ibm.com/developerWorks

Develop new visual UI features in HTML 5 Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 24 of 25

Page 25: Creating mobile Web applications with HTML 5, Part 5: Develop

• XML zone discussion forums: Participate in any of several XML-relateddiscussions.

• developerWorks blogs: Check out these blogs and get involved.

About the author

Michael GalpinMichael Galpin is an architect at eBay. He is a frequent contributor todeveloperWorks. He has spoken at various technical conferences,including JavaOne, EclipseCon, and AjaxWorld. To get a preview ofwhat he is working on next, follow @michaelg on Twitter.

Trademarks

IBM, the IBM logo, ibm.com, DB2, developerWorks, Lotus, Rational, Tivoli, andWebSphere are trademarks or registered trademarks of International BusinessMachines Corporation in the United States, other countries, or both. These and otherIBM trademarked terms are marked on their first occurrence in this information withthe appropriate symbol (® or ™), indicating US registered or common lawtrademarks owned by IBM at the time this information was published. Suchtrademarks may also be registered or common law trademarks in other countries.See the current list of IBM trademarks.Adobe, the Adobe logo, PostScript, and the PostScript logo are either registeredtrademarks or trademarks of Adobe Systems Incorporated in the United States,and/or other countries.Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in theUnited States, other countries, or both.Microsoft, Windows, and the Windows logo are trademarks of Microsoft Corporationin the United States, other countries, or both.Other company, product, or service names may be trademarks or service marks ofothers.

ibm.com/developerWorks developerWorks®

Develop new visual UI features in HTML 5 Trademarks© Copyright IBM Corporation 2010. All rights reserved. Page 25 of 25