Hour 2

New HTML5 Tags and Attributes with Mobile Development

What You’ll Learn in This Hour:

  • How to use the many new tags and attributes in HTML5
  • Other changes in HTML5
  • Mobile support for HTML5
  • Reasons to use HTML5 for mobile web applications

HTML5 has many new tags and attributes that you can use for building web pages and applications. In this hour you will learn about many of the new HTML5 features and how they work on mobile devices. The new smartphones and tablets are driving the adoption of HTML5, and this chapter tells you what you can do to be a part of the revolution.

The New HTML5 Tags

HTML5 adds a lot of new features to the HTML specification, but the easiest ones to understand are the brand-new tags. These are HTML elements that have never been a part of HTML in the past.

New Layout Tags

Most of these new tags are called “sectioning” elements and they provide semantics for the layout and sections of an HTML document. Hour 9, “Adding Meaning with HTML5 Sectioning and Semantic Elements,” covers these tags in more detail.

These tags are:

  • <article>An independent portion of the document or site.
  • <aside>Content that is tangential to the main part of the page or site.
  • <figcaption>Caption for a figure.
  • <figure>A figure or quotation pulled out of the flow of text.
  • <footer>The footer of a document or section.
  • <header>The header of a document or section.
  • <hgroup>A group of headings.
  • <nav>A navigation section.
  • <section>A generic section that cannot be defined by one of the above types.

You use these tags to define specific areas of your HTML documents. They provide you with ways to attach CSS styles (often called hooks for CSS) and give some semantic meaning to the parts of your pages.

Providing Meaning with Semantic Tags

Semantic tags tell the browser or user agent (a technical term for a tool that can parse web pages) something about the contents of the tag. In other words, rather than just defining where a block of text should appear in the page flow, a semantic tag such as <article> tells the browser that the contents are part of a stand-alone article.

Using these new layout tags is easy. In fact, many web pages already use <div> tags for the same purpose as these tags. For example, in many web designs you might see a <div id="header"> section of the page. Now, with HTML5, you can just write <header>.

You probably have a lot of web pages that have a markup similar to this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
    <title>My HTML 4 2-Column Page</title>
    <link type="text/css" href="styles.css">
</head>
<body>
    <div id="main">
        <div id="header">
            <h1>My HTML 4 2-Column Page</h1>
        </div>
        <div id="nav">
            <ul>
                <li><a href="#">Home</a></li>
                <li><a href="#">Products</a></li>
            </ul>
        </div>
        <div id="contents">
            <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit,
nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut
minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl
ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in
esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at
accumsan et iusto odio dignissim qui blandit praesent luptatum zzril
dolore te feugait nulla facilisi.</p>
        </div>
    </div>
    <div id="footer">
        <p>&copy; 2011 J Kyrnin</p>
    </div>
</body>
</html>

As you can see, there is a header, called <div id="header">, a footer <div id="footer">, a navigation area <div id="nav">, and an area for the main contents of the page <div id="contents">.

You can easily convert these <div> tags into HTML5 sectioning content tags:

<!doctype html>
<html lang="en">
<head>
    <title>My HTML 4 2-Column Page</title>
    <link type="text/css" href="styles.css">
</head>
<body>
    <section id="main">
        <header>
            <h1>My HTML 4 2-Column Page</h1>
        </header>
        <nav>
            <ul>
                <li><a href="#">Home</a></li>
                <li><a href="#">Products</a></li>
            </ul>
        </nav>
        <section id="contents">
            <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit,
nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut
minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl
ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in
esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at
accumsan et iusto odio dignissim qui blandit praesent luptatum zzril
dolore te feugait nulla facilisi.</p>
        </section>
    </section>
    <footer>
        <p>&copy; 2011 J Kyrnin</p>
    </footer>
</body>
</html>

Video 2.1 shows an example of converting to new layout tags.

Video 2.1.Converting to New Layout Tags


Listing 2.1:

Using the id Attribute

One thing you should note is that the new HTML5 elements, <header>, <footer>, <nav> and so on, represent more than just the page’s header, footer, and navigation. A page can have several of these elements, so adding an id attribute (for example, <nav id="mainNav">) is often helpful to help style the document. Hour 9 describes these elements in more detail.

Additional Semantic Elements

You can use a number of semantic elements in HTML5 to define specific items in your documents. Semantic elements let the browser or user agent know that the contents of the tag have a specific meaning beyond the meaning of the text itself. Hour 9 covers these tags in more detail. Here are the new semantic tags in HTML5:

  • <details>Control for adding more information.
  • <figcaption>Caption for a figure.
  • <figure>A figure or quotation pulled out of the flow of text.
  • <mark>Content that has been highlighted or marked.
  • <meter>A scalar gauge.
  • <output>Results from a script or form.
  • <progress>Progress indicator.
  • <summary>Summary or legend for a details element.
  • <time>Date or time.
  • <wbr>Optional line break.

One of the easiest new semantic elements to understand is the <time> element. This tag says that anything inside it is a time or a date. Calling out times and dates enables user agents to do things such as add calendar links automatically. Although no browser currently supports the <time> tag, Figure 2.1 shows how this tag might be used.

Figure 2.1. An example of an iPad evaluating a date element in an email message.

image

Semantic Tags May Not Do Anything

One of the most common complaints about semantic tags is that they don’t do anything. These tags are intended to provide additional information about the contents, and user agents may choose to simply leave them alone. This does not mean that the tags are useless. They provide hooks for CSS to style your pages more efficiently and they allow for the possibility that user agents will do something with them in the future. Plus, while your browser may not do anything with the tag, another browser might be using it extensively.

Don’t add content just to use semantic tags. Instead, when you see a section of your document that has a semantic meaning, enclose it in that semantic tag.

New Multimedia Tags

Some of the most talked about new tags in HTML5 are the multimedia tags. The following tags let you add multimedia elements right into your HTML:

  • <audio>Embedded sound files.
  • <canvas>Embedded dynamic graphics.
  • <embed>To add other technologies that don’t have a specific HTML5 element.
  • <source>The source files for embedded sound and video.
  • <track>Supplementary media tracks for embedded sound and video.
  • <video>Embedded video files.

The <canvas> tag lets you draw images right inside your HTML page (as well as other things). This gives you the ability to add custom fonts to your pages, create simple and very complex games, animate vector graphics, and control all these things from within the HTML itself. You don’t need any plug-ins or extra XML files. As you can see in Figure 2.2, the Android browsers already support the <canvas> tag.

Figure 2.2. A simple page with a <canvas> tag creating a big blue square on an Android tablet.

image

The HTML for Figure 2.2 is just one line:

<canvas id="simple-square" width="800" height="800"></canvas>

Adding some additional JavaScript in the <head> creates the square:

<script type="text/javascript">
    function drawSquare () {
        var canvas = document.getElementById('simple-square');
        if (canvas.getContext) {
            var context = canvas.getContext('2d');

            context.fillStyle = "rgb(13, 118, 208)";
            context.fillRect (2,2,798,798);
        } else {
            // put code for browsers that don't support canvas here
            alert("This page requires an HTML5 compliant browser to render correctly. Other browsers may not see anything.")
        }
    }
</script>

Don’t Forget to Load Your Script

If you use the preceding script to add a <canvas> square to your web page, don’t forget to change your <body> tag to load the script to <body onload="drawSquare()">. Otherwise, your <canvas> will remain blank.

Hour 10, “Drawing with the HTML5 Canvas Element,” covers the <canvas> tag in more detail.

HTML5 has some other interesting additions to the language. For example, now the <embed> tag is a valid part of the specification. Up until HTML5, the <embed> tag was supported by most browsers but was not valid HTML, so you couldn’t use it if you needed your pages to validate.

HTML5 also introduces the <audio> and <video> tags to embed audio and video files directly in your HTML just like you would an image with the <img> tag. You can use the <track> and <source> tags to support these new multimedia tags.

Embed Any Type of Video or Audio

The great thing about HTML5 multimedia is how flexible it is. You can use the <video> and <audio> tags to embed any type of video or audio file that you can save on a computer. Not all types will play in the browsers, but this flexibility means that when formats improve, your web pages won’t need to change to a new tag.

Hour 12, “Audio and Video in HTML5,” goes into more detail about HTML5 video and audio support.

New Form Features

HTML5 forms have a lot more functionality than HTML 4 forms did. You can now collect form field data of many different types beyond the standard text fields, drop-down menus, and other types common to HTML 4 forms.

With HTML5 you can set up form <command> tags to define a single action for multiple form elements. You can provide pre-defined data in a <datalist> tag. With the <keygen> tag you can generate public-private key pairs to keep your forms secure. And best of all, the <input> tag now has 13 new types for collecting specific data:

  • <input type=color>
  • <input type=date>
  • <input type=datetime>
  • <input type=datetime-local>
  • <input type=email>
  • <input type=month>
  • <input type=number>
  • <input type=range>
  • <input type=search>
  • <input type=time>
  • <input type=tel>
  • <input type=url>
  • <input type=week>

The new input types will work in every browser out there. Even if they don’t do anything special with the tags, all browsers will display a form text field for collecting data. As you can see in Figure 2.3, browser support is still growing, but using types such as <input type="tel"> will provide additional functionality for those browsers and user agents that can support it.

Figure 2.3. On the left is a form in Safari and on the right the same form (zoomed in) on an iPod touch.

image

You will learn a lot more about HTML5 forms in Hour 13, “HTML5 Forms.”

Improved International Support

Five new tags in HTML5 help improve the support for non-English language documents. These tags are

  • <bdi>
  • <meta charset>
  • <rp>
  • <rt>
  • <ruby>

The <bdi> tag lets you change the direction of text that is written in HTML. So if you have a document written in English (a left-to-right directional language) and you want to add some Hebrew (a right-to-left directional language), you can surround the Hebrew with the <bdi> tag to indicate that the direction has changed for that span of text.

The <meta charset> tag lets you define the character encoding that your web page is using. For example, to define your HTML as using the utf-8 character set, you would write:

<meta charset="utf-8">

Finally, if you write HTML with double-byte languages such as Chinese and Japanese, you may already be familiar with ruby characters. These are small glosses placed next to the characters, usually to indicate pronunciation. The <ruby> tag indicates the span of ruby characters and can include <rt> for ruby text and <rp> for parentheses around the ruby text. Here is an example using pseudo-code:

<ruby><rp><rt>ruby text</rt></rp></ruby>

The New HTML5 Attributes

Many of the new attributes in HTML5 extend the tags they are associated with. A bunch of new event attributes enable you to associate scripts to many more actions as they happen on your web page. Plus, you can use new global attributes that apply to all HTML5 elements.

An attribute is written in HTML after the tag name, separated by a space, inside the greater-than and less-than signs. If the attribute can have a value, that value is attached to the attribute by an equal sign. If spaces exist in the value, then you should surround the whole value with quotation marks. For example:

<elementname attributename=value>

Or:

<element name="value value">

Boolean attributes are also available in HTML5 that don’t require a value. Instead, if they are present, the attribute is applied, and if they are absent the attribute is not applied. Following is an example:

<elementname attribute>

The most well-known Boolean attribute in HTML 4 is the checked attribute on checkboxes:

<input type=checkbox checked>

Event attributes indicate an event that might happen when the page is loaded. The new HTML5 event attributes include:

  • onabort—Fires when an action is aborted.
  • onbeforeonload, onbeforeonunload, and onunload—Fires just before an element loads or unloads and as an element unloads.
  • oncontextmenu—Fires when the context menu is triggered.
  • ondrag, ondragend, ondragenter, ondragleave, ondragstart, and ondrop—These fire when various drag-and-drop actions occur.
  • onerrror and onmessage—These fire when errors or messages are triggered.
  • onscroll—This fires when the user scrolls the browser scroll bar.
  • onresize—Fires when an element is resized.

You can use these event attributes on nearly every element in HTML5, which gives you much flexibility in how your web applications react to events.

HTML5 also adds a bunch of new global attributes that you can apply to nearly every HTML element. The new global attributes are:

  • contenteditable
  • contextmenu
  • draggable
  • dropzone
  • hidden
  • spellcheck

Contenteditable and spellcheck allow you to set some elements to be editable inside the browser, and while they are edited, the browser can check the spelling. Hour 14, “Editing Content and User Interaction with HTML5,” describes these elements in more detail.

Draggable and dropzone provide elements that can be dragged and places to drag them to. Hour 16, “Working with HTML5 Drag-and-Drop Functionality,” covers more about using drag-and-drop within your applications.

The contextmenu attribute allows you to define a menu that appears only when you right-click or mouse over an element. Hour 17, “HTML5 Links,” provides you more information about this attribute.

The hidden attribute has the same action as writing display: hidden; in CSS, but it also allows you to semantically describe an element that is currently not relevant to the page, such as a form element that only is required if they fill out other fields in a specific way. This feature is most useful for accessibility, because screen readers would not read out the contents of an element that is hidden, but they might if only the CSS was hiding it.

Changes to HTML 4 Tags and Attributes

A number of changes have been made to existing tags and attributes in HTML 4 to give them a wider functionality or to change their function, more clearly define their meaning and scope, or to provide a semantic definition.

For example, a number of tags that didn’t have a semantic aspect to them in HTML 4 have been given semantic meanings in HTML5, including:

  • <b>Text that would normally be displayed as bold.
  • <i>Text that would normally be displayed as italics.
  • <hr>A paragraph-level thematic break in the text.
  • <s>Content that is no longer accurate or relevant.
  • <small>Small print such as in legal documents.

A few tags have had their meaning changed or had a new use added:

  • You can now write the <a> tag with no attributes. In this situation it is considered a placeholder for a link.
  • The <address> tag is now part of sectioning content (see Hour 9).
  • The <cite> tag now represents the title of a work, but you cannot use it to mark up the name of a person.
  • With the <menu> tag you can create toolbars and context menus.
  • A few elements have also had features or descriptions changed or removed:
  • The <dl> tag is now a list of name=value pairs, and should not be used for displaying dialog like a script.
  • When displaying the <label> element, user agents should not move the focus from the label to the control unless that is standard behavior for the platform.
  • The <strong> element now indicates importance rather than strong emphasis.
  • You can no longer include <object> elements inside the <head> element.

Most HTML 4 attributes have remained the same, but you no longer have to have the type attribute on <script> and <style> tags, unless you are using nonstandard scripts (that is, not JavaScript) or style sheets (that is, not CSS).

A few attributes exist that, while allowed, HTML5 strongly recommends you find alternate solutions for, as described in the following situations:

  • If you include the border attribute on an <img> tag to turn off the border, you must give it a value of “0,” for example border=0. Using CSS, such as img {border: none;} is better.
  • If you use the language attribute on a <script> tag, it must say “javascript” (case insensitive) and cannot conflict with the type attribute. Simply leaving out this attribute is better because it has no useful purpose.
  • If you use the name attribute on an <a> tag, you should change that to use the id attribute instead because the name attribute is obsolete.
  • If you write complex tables and want to provide a summary using the summary attribute, you still can. However, putting that summary in the surrounding text, inside a table <caption>, inside a <details> element of the caption, or inside a <figure> or <figcaption> that the table is also a part of is better because it is more accessible.
  • If you use images with the width attribute, you can no longer use percentages for the width.

Also, you should no longer use a few elements and attributes; they are considered obsolete in HTML5. This hour won’t go over all of them in detail, but if the element or attribute you are considering using is not in the HTML5 elements and attributes list in Appendix A, you should consider using another option.

The most noticeable omissions are

  • <frame>, <frameset>, and <noframes>—Frames are no longer in HTML5, so you cannot use these.
  • <basefont>, <big>, <center>, <font>, <strike>, <tt>, and <u>—These tags have been removed because they are purely presentational and their function is better handled by CSS.
  • <acronym>—This tag was removed because it was confusing. Use <abbr> for abbreviations instead.
  • <applet>—This tag has been made obsolete in favor of <object>. Similarly, the <dir> tag has been dropped in favor of <ul>. These were dropped because the replacement element is more accessible or easier to use.

Changes to HTML Syntax in HTML5

HTML5 does not offer a large number of syntax changes from HTML 4. You still surround tags with greater-than and less-than characters, you still start your documents with a doctype, and you still enclose your document contents inside the tags.

The biggest change that most people will notice is the doctype. As mentioned in Hour 1, “Improving Mobile Web Application Development with HTML5,” it has been radically simplified. All you need to write is

<!doctype html>

Plus it can be in all lowercase, uppercase, or even mixed case if you like.

If you use an HTML generator that can’t use the short doctype, you can add a doctype legacy string to the doctype, as follows:

<!DOCTYPE html SYSTEM 'about:legacy-compat'>

Like HTML 4 (not XHTML), you can write your tags in any case you want. The <html> tag is the same as <HTML> and <hTmL>. Most designers use lowercase because it’s easier to read. You also don’t have to quote attributes unless a space exists in the value. However, if you think you’re ever going to convert your HTML to XHTML, consider using lowercase tag names and attributes and continue to quote all your attributes.

Mobile Support of HTML5 Tags and Attributes

Older mobile devices, such as non-smart phones and older PDAs, don’t have support for HTML5 and probably never will. But the reality is that mobile devices are moving beyond those devices at a break-neck speed.

The majority of smart phones and tablets being put out today have good (if not perfect) HTML5 support. Both Android and iOS devices (as well as phones and tablets by Nokia, Palm, and Rim) use browsers based on the WebKit browser, which has good HTML5 support that gets better every day.

Interestingly, Windows mobile devices are the one holdout in this category. As recently as August 2010, Microsoft was saying it was not going to support HTML5 in its Windows 7 mobile devices. But that changed in 2012, when the Windows phone came out with Internet Explorer 10 and full HTML5 support.

Unfortunately, being able to design a web page or application, test it in one browser, and expect it to work in all devices is not possible. But mobile devices, especially Android and iOS, will drive HTML5 development. These devices already have extensive support for HTML5 and more is added all the time.

Benefits of HTML5 for Mobile Web Development

Remember that HTML5 is not available for every mobile device in every mobile web browser. As mentioned earlier, many older devices, non-smart phones, and tablets don’t have good HTML5 support. But for those that do support it, a lot of great reasons exist for moving to HTML5 for your mobile development.

HTML5 Includes APIs That Work Well

HTML5 introduces Application Programming Interfaces, or APIs, for video, audio, web applications, editing content on the page, drag-and-drop, and exposing the browser history. These all work well with mobile because they mean that the mobile browser won’t need a plug-in or add-on to get these features to work. If the browser is HTML5 compliant then it will support these APIs. This book will cover how to use several APIs in other Hours.

Plus, HTML5 and the Open Web Standard have APIs for geolocation, web storage, and offline web applications that are well suited for mobile devices. Most smart phones and tablets have a GPS or other way of determining location that can use geolocation features. Web storage helps turn a standard web page into an application with saved data that can be kept with you at all times on your mobile device. Offline applications are important when the phone isn’t connected to the internet. In fact, a mobile device is more likely to need offline capabilities than most desktop computers.

HTML5

Getting into mobile development can seem daunting. For the average web developer, Objective C is virtually unintelligible. But developers already know HTML 4, CSS, and JavaScript, and with those three languages you can build robust applications using HTML5 and the Open Web Standards.

This means that if you’ve built any web pages before, you can be up and running with mobile applications in a short period of time (24 hours or less, in fact) because you already know the basics of the languages involved.

Customers Prefer Web Applications

In a study done in late 2010, in nearly every category examined (except for games, music, and social media) people preferred using their mobile browser rather than a separate app.

Although it’s true that applications are getting more and more popular, web applications offer the best of both worlds. You can create an HTML5 web application that runs in the mobile browser, so users can bookmark it and use their familiar tool, but it also contains the features and functionality of a typical application.

Also, when you build an HTML5 web application for a mobile device, that application will work on HTML5 browsers on non-mobile devices as well. Depending upon how you code your application, you might not need to create anything more than a different stylesheet for standard web browsers and mobile devices. Maintaining this is much easier than having to create a separate application for every platform that comes out.

Summary

In this hour, you learned the new HTML5 tags and attributes and the HTML 4 tags and attributes that have changed in HTML5. You also learned the changes in syntax that HTML5 added. The new tags are the bulk of the change to the HTML5 language, and you learned the basics for adding them into your documents.

This chapter also covered some of the reasons why HTML5 is well suited for mobile devices, including the APIs that have been added to the standard, how this affects development of HTML applications, and the usage patterns of customers on mobile devices (and off).

Q&A

Q. Where can I go to learn more about the new HTML5 tags and attributes?

A. Many of these new tags and attributes will be discussed in later hours of this book. But you can always get the most up-to-date information by going to the W3C site at www.w3.org/.

Q. I want to get started using HTML5 tags right now, how can I tell whether I’m writing them correctly if the browsers don’t support them?

A. Web browser support has long been a struggle for most web developers, and HTML5 has not changed that situation. But an experimental HTML5 conformance checker is available at the W3C (http://validator.w3.org/), and you can find another highly experimental validator at http://html5.validator.nu/. Using a validator isn’t the same as testing, but it will tell you whether you’re using the tags correctly.

Q. What if a lot of my customers use Internet Explorer 8 or older? Will these new HTML5 tags work in their browsers?

A. Internet Explorer 8 is the only modern browser that does not support HTML5 tags. If you need to support this browser, then consider using a workaround such as the HTML Shiv. To use it, you add this code snippet to the <head> of your documents:

<!—[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]—>

Quiz

Quiz Loads Here

 

 

 

Exercises

  1. Create an HTML page with the sectioning elements discussed in this chapter. Include at least one <section>, <header>, <nav>, and <article>.
  2. Open your HTML5 page on a mobile device. The easiest way to do this is to put your page up on a web server and then browse to it on your phone or tablet. If you have access to both an Android and an iOS device, try viewing it in both to get in the habit of testing.