Smashing html5 by Bill Sanders
Smashing html5 by Bill Sanders
Smashing html5 by Bill Sanders
HTML5
PUBLISHERS ACKNOWLEDGMENTS
Some of the people who helped bring this book to market include the following: Editorial and Production VP Consumer and Technology Publishing Director: Michelle Leete Associate DirectorBook Content Management: Martin Tribe Associate Publisher: Chris Webb Publishing Assistant: Ellie Scott Development Editor: Elizabeth Kuball Copy Editor: Elizabeth Kuball Technical Editor: Harvey Chute Editorial Manager: Jodi Jensen Senior Project Editor: Sara Shlaer Editorial Assistant: Leslie Saxman Marketing Senior Marketing Manager: Louise Breinholt Marketing Executive: Kate Parrett Composition Services Compositor: Wiley Composition Services Proofreader: Susan Hobbs Indexer: Potomac Indexing, LLC
SMASHING
HTML5
Bill Sanders
This edition first published 2011 2011 William B. Sanders. Registered office John Wiley & Sons Ltd, The Atrium, Southern Gate, Chichester, West Sussex, PO19 8SQ, United Kingdom
For details of our global editorial offices, for customer services and for information about how to apply for permission to reuse the copyright material in this book please see our website at www.wiley.com. The right of the author to be identified as the author of this work has been asserted in accordance with the Copyright, Designs and Patents Act 1988. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, except as permitted by the UK Copyright, Designs and Patents Act 1988, without the prior permission of the publisher. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books. Designations used by companies to distinguish their products are often claimed as trademarks. All brand names and product names used in this book are trade names, service marks, trademarks or registered trademarks of their respective owners. The publisher is not associated with any product or vendor mentioned in this book. This publication is designed to provide accurate and authoritative information in regard to the subject matter covered. It is sold on the understanding that the publisher is not engaged in rendering professional services. If professional advice or other expert assistance is required, the services of a competent professional should be sought. Trademarks: Wiley and the Wiley Publishing logo are trademarks or registered trademarks of John Wiley and Sons, Inc. and/ or its affiliates in the United States and/or other countries, and may not be used without written permission. iPhone, iPad and iPod are trademarks of Apple Computer, Inc. All other trademarks are the property of their respective owners. Wiley Publishing, Inc. is not associated with any product or vendor mentioned in the book. This book is not endorsed by Apple Computer, Inc. A catalogue record for this book is available from the British Library.
978-0-470-97727-9 Set in 10/12 Minion Pro by Wiley Composition Services Printed in the United States by Krehbiel
Authors Acknowledgments
I became aware of the immediate importance of HTML5 thanks to Michael Wilson, Zach Dunn, and Nick Greenfield, who brought it to my attention. They also introduced me to Smashing Magazine and a number of other emerging new trends. Chris Webb of Wiley guided the direction of the book and, in concert with Margot Hutchinson of Waterside Productions, was able to clear a path for the book to move ahead. Ellie Scott of Wiley helped take care of the many details necessary in forging the books inception. Elizabeth Kuball worked as an able editor to clarify and smoothen everything I wrote, and Harvey Chute, the technical editor, worked to make sure that all the code was done correctly and offered suggestions for improvement. Finally, my colleagues at the University of Hartfords Multimedia Web Design and Development program, John Gray and Brian Dorn, helped when asked, including one terrible moment when a missing semicolon wrecked havoc on a program.
Contents
Introduction 1
5
1 8 9 11 15 17 18 19 21 22 24 24 25 27 28 28 31 31 32 32 33 35 38 40 43 44 45 47 49 52 52 59 63
CONTENTS
Chapter 4: Working with Color Values Understanding RGB Color Using names RGB and HSL percentages RGB decimal integer settings Hexadecimal settings: Thinking like your computer Adding Transparency to Color Creating a Color Scheme From a base color From an image Integrating Your Color Palette with Your Web Page Take the Wheel 65 66 66 67 70 71 74 76 76 76 78 81
83
85 86 86 87 89 91 94 94 99 100 103 103 104 104 106 109 110 112 113 114 114 117 120 120 122 125 127 128 128 131
VIII
CONTENTS
Prefetching Other link attributes Page Links More of the rel attribute Page anchors and IDs Targets Using Iframes Nesting Web pages Take the Wheel Chapter 8: Navigation Strategies Web Navigation Concepts Designer navigation and user navigation Global navigation Using JavaScript to Call a Linked Page Creating Consistency Vertical and horizontal navigation Applying CSS3 pseudo-classes Understanding the HTML5 mechanics of vertical navigation Using graphic icons in navigation Single-Page Web Sites with Iframes Linking to a graphic Making and using thumbnail icons Using iframes on mobile devices Take the Wheel 133 133 134 134 137 140 143 144 146 147 148 148 149 156 159 160 160 162 165 166 166 167 169 170
IX
173
175 176 176 178 179 182 189 189 191 194 196 199 200 200 200 202 203 203
CONTENTS
Saved by Source: Plan B Type attribute Source type codec parameter Creating Audio Files Windows 7 Sound Recorder Macintosh OS X Sound Studio Sound Effects: FX on Your Desktop Transition sounds Integrating sound effects into a Web page Take the Wheel Chapter 11: Video Making an HTML5 Page with Video Video and Browser Compatibility Make mine WebM: The Miro Video Converter Converting to 3GP: Adobe Media Encoder CS5 Making Videos for the Web Webcams Small camcorders Standard camcorders Screen video capture Video and Source Attributes Src Poster Preload Loop Autoplay Controls Width and Height Take the Wheel 204 204 205 206 206 208 209 209 211 214 215 216 218 219 221 222 223 223 224 225 225 226 226 227 227 228 228 229 229
PART IV: DYNAMIC HTML5 TAGS PLUS A LITTLE JAVASCRIPT AND PHP
Chapter 12: Adding Just Enough JavaScript Inserting JavaScript into HTML5 Pages JavaScript in external files Functions Event handlers Using the Document Object Model How the DOM works with your page and JavaScript HTML5 elements and the DOM Storing Temporary Values Variables Arrays Objects Take the Wheel
231
233 234 234 235 236 239 240 242 244 244 248 249 252
CONTENTS
Chapter 13: Thundering Your Site with Canvas Canvas Basics A simple canvas implementation Images in canvas and shadows Creating Complex Drawings with Canvas Lines and movement Curves Take the Wheel Chapter 14: Adding Forms Adding a Form General form attributes The form as part of the DOM The Many Kinds of Input The list attribute, the URL type, and datalists Radio buttons and check boxes: Easy-to-select input elements Date picker Take the Wheel Chapter 15: Embedding Objects and Storing Information Geolocation Finding latitude and longitude Getting the map Working with the geolocation properties and the Google Earth plug-in Storage in HTML5 Session storage Local storage Adding and Adjusting Objects in HTML5 Web Pages Adding an object Adjusting an object Take the Wheel Chapter 16: Catching Interactive Data Server-Side Languages and HTML5 Setting up PHP on your computer (which thinks its a server) Testing PHP PHP Basics The post catcher Data validation Basic PHP Program Structures Temporary data storage Key PHP operators Making an E-Mail Application A simple e-mail application PHP catch and send Adding a header and auto-reply in PHP Take the Wheel Index 253 254 256 264 269 270 275 281 283 284 286 290 293 294 297 301 303 305 306 306 307 310 311 312 316 320 320 322 322 325 326 326 327 328 330 330 332 332 336 337 338 340 342 344 345 XI
Introduction
In 1992, I was stumbling the Internet (we used to stumble prior to surfing) with a program using the Gopher protocol. From El Paso, Texas, I was able to look up the train schedule between London and Cambridge in England. At the time, it was like a miracle. Here I was in West Texas with a London-Cambridge train schedule. Unbelievable! Shortly after that time when I didnt think it could get any better than Gopher on the Internet, up popped the Mosaic browser and the World Wide Web. Netscape Navigator soon supplanted Mosaic, and I discovered HTML. Now I was able to see graphics and text plus I could link to other Web pages. In short order, I worked out how to create my own Web pages using a text editor and the new markup language, HTML. Some of the guys in computer services set up a host for me, and I was in business. For a while, it seemed that a new version of HTML was coming out every year or so. CSS and JavaScript were introduced and more and more browsers became available. It just kept getting better and better, but after HTML4 (in its many forms, including XHTML), things seemed to stagnate. This HTML Dark Ages lasted from about 2000 to 2008. Then the World Wide Web Consortium (W3C) published the HTML5 Working Draft in 2008. However, after publication of the HTML5 standards in a draft format, everything was back to a crawl as far as getting my hands on an HTML5 browser. The team developing the standards has been methodical in the development process and was planning on implementing the final draft of the standards in browsers in 2012! Then one day in 2009 or 2010, I read about a beta version of a browser that supported HTML5, or at least some of its features. By 2010, several browsers were supporting HTML5, including browsers made for mobile devices. Online blogs like www.smashingmagazine. com were publishing posts about HTML5 and so, ready or not, HTML5 was here! Somehow HTML5 has escaped from the zoo, and the race was on to produce HTML5 browsers. We have officially entered the HTML Renaissance Period. The excitement is back! HTML5 is so big that I had to select a focus that would encompass the essence of the markup language without devolving into a mere reference or encyclopedia attempting to touch on everything and explain nothing. Naturally, the new features were going to be a major focal point, but they exist in the context of a host of other tags, and readers learning HTML for the first time need foundational elements. Also, I had to drop the discontinued elements like a bad habit and show how the continued and new elements work in concert. Further, CSS3 and JavaScript play an important role, but theyre only introduced insofar as they relate to HTML5. (Smashing JavaScript and Smashing CSS cover these important features in detail.) So Ive divided Smashing HTML5 into four parts that bring together the heart and soul of HTML5.
INTRODUCTION
PART IV: DYNAMIC HTML5 TAGS PLUS A LITTLE JAVASCRIPT AND PHP
One of the most anticipated features of HTML5 has been the canvas element. However, in order to get the most out of canvas, you need both JavaScript and CSS3. So, in this part, you learn enough JavaScript with the HTML5 Document Object Model (DOM) to work effectively with canvas and CSS3. Likewise, HTML5 brought with it several new form attributes, but as with most forms, they need help for processing the information. Using JavaScript,
INTRODUCTION
youll learn how form data can be saved with the new storage objects in HTML5. Also, youll learn how to use PHP to process information entered in HTML5 forms so that you can automatically send and receive e-mails via the Web. Also, I take a look at the new geolocation objects and their properties and show you how you can have your Web page automatically load a map based on your current latitude and longitude coordinates. Youll find Part IV full of new materials that will add many new features to your site.
Chapter 1: Introducing HTML5 Chapter 2: Understanding HTML5 Tags Chapter 3: Text Tags and a Little CSS3 Chapter 4: Working with Color Values
PART
SMASHING HTML5
INTRODUCING HTML5
about some of the new browsers that are specifically developed for mobile devices, so you can test HTML5 pages on your mobile device, too. To get started, download all the HTML5 browsers (covered in this chapter) so that you can learn what users will see when they encounter an HTML5 Web page that youve created.
THIS CHAPTER IS a general overview of whats new, whats the same and whats been removed from HTML that makes HTML5. At this time, one of the most important tasks is to find out which browsers work with HTML5, which ones are in development that promise HTML5 compatibility and how each has started to implement HTML5. Also, youll want to learn
CHAPTER
Opening tag Container = between opening and closing tags. The <p> tag is inside the <body> container and Hello is inside the <p> container. Closing tag
tells the interpreter in your browser to create big text that looks like this:
Table 1.1
New Element
<figcaption> Caption tag for the gure element <figure> <footer> <header> <hgroup> <keygen> <mark>
Contains a group of media content and their caption Container for a footer for a section or page Container for header for a section or page A heading of a section with multiple h1 to h6 elements in a document The key pair generator control representation. A string of text in one document, marked or highlighted for reference in another document continued
(continued)
Description
Container for a known range of values (for example, disk use) Representation of a section of a document intended for navigation Denes the progress of a task of any kind Representation of the progress made in a task (such as percentage complete in a download operation) Indicator in Ruby (a programming language) annotations to dene what to show browsers that dont support the <ruby> element Marks the ruby text component of a ruby annotation Element for spans with ruby annotations Theme identier for content grouping Container for multiple specication of media resources Information on a <details> element Container for a date/time Element for linking to a video le Representation of a line break opportunity to guide the hyphenation of long words or text strings
<meter> <nav> <output> <progress> <rp> <rt> <ruby> <section> <source> <summary> <time> <video>
10
<wbr>
Some of the new elements, like <video> and <audio> add multimedia to HTML and represent a major new capacity to HTML. Others, like <ruby>, are quite specialized, and unless you need certain East Asian characters, youre unlikely to use that element. One characteristic of many of the new tags is that they work in conjunction with CSS3 or JavaScript. However, most of the new elements still work on their own, without any added help. When adding a style or some of the cooler features, you may find yourself using a bit of CSS3 or JavaScript, but you dont have to learn the entire JavaScript language or even CSS3 to have some fun with it. For example, the following script uses the new <datalist> element that has not been available in earlier versions of HTML. Enter the following code in a text editor, save it as Datalist.html, open it in your Web browser, and youll see how it assists users in entering data. (You can find Datalist.html in this chapters folder at www.wiley.com/go/ smashinghtml5.)
<!DOCTYPE HTML> <html> <head>
When you open the file in an Opera browser, youll be given a list of input options, as shown in Figure 1-2.
11
Unlike earlier versions of HTML, in which text input didnt show the user an options list, this one does.
PART I:THE LANGUAGE OF THE WEB Table 1.2 Continued Tags from Previous HTML Versions
Description
A comment The document type (only one in HTML5) Hyperlink to a page or page area An abbreviation Container for an address An area inside an image map Bold text A base URL for all the links in a page Direction of text display A block of text Beginning a body element A single line break A clickable button A table caption Container for a citation Format for computer code text Denes attributes for table columns Container for groups of table columns Container for a value for the <dt> element Container for deleted text Representation of the dening instance of term Demarcation of division in a document Head for an association list Specication for a name in name-value group (description list) Emphasized text Container for a set of form controls Container for a form typically with input elements Text header 1 to header 6 Container for the rst code to be interpreted by browser Horizontal rule (line)
Continued Tags
<!--...--> <!DOCTYPE> <a> <abbr> <address> <area> <b> <base> <bdo> <blockquote> <body> <br> <button>
12
<caption> <cite> <code> <col> <colgroup> <dd> <del> <dfn> <div> <dl> <dt> <em> <fieldset> <form> <h1> to <h6> <head> <hr>
Continued Tags
Description
Container for an HTML document Italic text Frame an inline sub window Image container User-input eld within a form container Container for inserted text within implied paragraph boundaries Container for user keyboard input Representation of a caption in a user interface Title in a eldset border List item indicator A resource reference (for example, CSS) Image map container Text in one context marked for text in different context Container for a list of commands Container for meta information Container for embedded object (for example, a SWF le) A numbered (ordered) list An option grouping header in an options list Container for individual options in a drop-down list A paragraph block Plug-in parameters Preformatted text format Enclosed text with quotation marks Computer code output or snippet Container for script for CSS, JavaScript, or another recognized script A selectable list Small text Inline section in a document Strong text that looks like bold Container for a style denition continued
<html> <i> <iframe> <img> <input> <ins> <kbd> <label> <legend> <li> <link> <map> <mark> <menu> <meta> <object> <ol> <optgroup> <option> <p> <param> <pre> <q> <samp> <script> <select> <small> <span> <strong> <style>
13
(continued)
Continued Tags
Description
Subscripted text Superscripted text A table denition Demarcation for a block of rows for a tables body A table cell A text area container Representation for a block of rows of column summaries for a table Table header format Representation of a block of rows of column summaries for a table header The document title Demarcation of a table row An unordered list (a bullet list) Variable style in formula
14
Most of the elements with the same names from HTML4 are the same in every way in HTML5, but some have slightly modified meanings. Also, rules for some tags have changed. For example, in creating tables, the tag for specifying a row <tr> no longer requires a closing </tr> tag. Some attributes for elements have changed as well. As you continue to learn about the new features of HTML5, youll find that many of the old elements have lots of new characteristics. The following HTML table script provides a new example with old elements. Enter this text into your text editor, save it as NewOldTable.html, and open it in an Opera browser.
<!DOCTYPE HTML> <html> <head> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>Table</title> </head> <body> <table> <caption> =Element Types= </caption> <thead>
15
Figure 1-3: A table created with HTML5.
Generally, you dont use tables for formatting text. Instead, tables are used for formatting data such as data thats loaded from a database or created dynamically by another program like JavaScript. In HTML5, though, tables used in conjunction with CSS3 do a bit more formatting than in previous versions of HTML and CSS.
Discontinued Tags
Removed or Replaced
Replaced by <abbr> Replaced by <object> Better handled by CSS Replaced by <audio> Better handled by CSS Removed in HTML5 Better handled by CSS Replaced by <ul> Removed in HTML5 Removed in HTML5 Removed in HTML5 Replaced by explicit <form> Removed in HTML5 Removed in HTML5 Removed in HTML5 Removed in HTML5 Only conforming to HTML syntax Better handled by CSS Removed in HTML5 Better handled by CSS Better handled by CSS Better handled by CSS
<acronym> <applet> <basefont> <bgsound> <big> <blink> <center> <dir> <font> <frame> <frameset> <isindex> <marquee>
16
One of the most common discontinued tags is <center>, but you can easily center text using a little CSS, as shown in the following example. Type this text into your text editor, save it as CenterMe.html, and open it in your Web browser.
<!DOCTYPE HTML> <html> <head> <style type=text/css> h1 { text-align:center; }
All youre going to see when you test the code in your browser is: Headers Can Be Centered It may look like a lot of work to get a simple centered header, but pages are generally short, and you can center any header with an <h1> tag because youve changed the behavior of the tag. You can change any tag you want with CSS. (Youll learn about CSS3 in Chapter 3, but youve already used it if you see the header in the middle of your page.)
17
18
GOOGLE CHROME
Google, famous for its search engine and maps, created its browser, Chrome, from the ground up with HTML5 in mind. It has browsers for Apple, Windows, and Linux operating systems all available for free. Figure 1-5 shows the same exact Web page on the same computer as Figure 1-4 see if you can detect the differences.
19
Figure 1-5: Google Chrome displaying the same HTML5 page as shown in Figure 1-4.
Other than the different styles of the two browsers, it can be difficult to see the differences in the page. With a simple page, subtle differences wont affect how your Web page looks. However, as your pages get bigger and more complex, small differences can grow.
20
Part of the difference is due to the ways in which Windows and the Macintosh operating systems display text and user interfaces (UIs). Another view that Browserlab provides is called an onionskin; it superimposes one over the other and you can see more precisely where text and UIs appear. Figure 1-7 shows this difference. The blurrier an onionskin appears, the greater the differences in the way the Web page materials are rendered. In Figure 1-6, you can see that the view is very blurry, indicating that some key differences exist between the browsers and operating systems.
21
OPERA
When I was examining the Opera browser at the time of initially testing the different browsers, it seemed to have the best HTML5 features actually working. Plus, Opera has a special browser, Opera Mini 5, that you can download free for your mobile devices. HTML5 works fine on mobile devices, as you can see in Figure 1-8, which displays the sample Web page on an iPhone using Operas mobile browser.
22
Full-size Opera browsers are available for Windows, Macintosh, and Linux operating systems as well. When creating Web pages, you should plan for different size devices. As you can see, the sample application weve been using can fully fit in a mobile device as well as on large screens.
APPLE SAFARI
Apple makes Safari browsers for Macintosh and Windows as well as for mobile devices. For comparative purposes, Figure 1-9 shows how the sample application looks on Apples Mobile Safari, developed for the iPhone. Compare this with Opera Mini 5 in Figure 1-8.
23
Just as there are few differences between the appearances of the Web pages as viewed on a desktop or laptop computer, you shouldnt see many differences between what different browsers show on mobile devices. Thats a good thing! Web developers waste a good deal of time trying to make sure that all their pages look the same on different browsers and platforms. With a common implementation of HTML5, that shouldnt be a problem. Other unique features on browsers, such as having tabs, or other characteristics that make Web browsing easier, are fine as long as the browsers implementation of HTML5 is implemented according to the specifications defined by the World Wide Web Consortium (W3C).
24
25
You can change the device dimensions. For example, a Motorola Droid displays an 854 x 480 screen and a Sony VAIO UX displays a 1024 x 600 screen. The multiscreen preview helps you decide how to set up your page to optimize it for your viewers. Finding the best compromise is an art and one that can be made less onerous by knowing as much as possible about your audience and the devices theyre likely to use to view your materials.
26
When you test it in a browser, see if it looks like what you expected. Also, you might want to see what it looks like in different browsers and on your mobile device. (Remember: Web browsers are free.) If you want to make some more changes, go to www.w3.org/TR/ css3-color/#svg-color. There youll find a list of all the color names you can use with HTML5. See if you can change the color names in the code to ones you like.
SMASHING HTML5
PROGRAMMERS CHARACTERIZE COMPUTER languages as ranging from low-level languages that virtually mimic the native language of the computer to high-level languages that are close to how people talk. HyperText Markup Language Version 5 (HTML5) is a very high-level language. However, the original HTML had very few words with which to describe what the developer and designer wanted. As the Web grew, the demands on HTML grew. With help from Cascading Style Sheets (CSS) and JavaScript, designers could do more with Web pages, but still, a lot was lacking. More help was available for creating Web pages in the form of plug-ins that were able to run
CHAPTER
PARSING CODE
Sooner or later, youll hear the phrase parsing code in reference to browsers and HTML5, CSS3, and JavaScript. All that means is that the browser is reading the code and interpreting it to do what its told to do. Its just like an international interpreter who speaks English and Russian the interpreter parses Russian so that the English speaker understands it and English so that Russian speaker understands it. Strictly speaking, the parser is part of the interpreter in the browser, but for all practical purposes, just think of parsing as involved in getting the Web page to do what you told it to do in the tags you used in your Web file. In order to correctly parse HTML5, two things have to happen: You have to write the code correctly, and your browser has to interpret it correctly. Thats why standards are important. Basically, standards insure that when you write HTML5 code according to the rules set down, your code does what you expect it to do in all browsers and on all computers. Using HTML5, CSS3, and JavaScript with the browsers discussed in Chapter 1, you shouldnt have any surprises when theyre all fully HTML5 compliant. Ironically, the standards allow for the most designer and developer creativity. If you want to have the page look or act in a certain way, following the standards used by the browsers that interpret your creations, theyll look the way you want them to look and behave as expected. If either you or the browser fails to follow the standards, your creativity is ruined. (We dont want that now, do we?) 28
.jpg (JPEG graphic file) .gif (GIF graphic file) .png (PNG graphic file) .svg (SVG graphic file) .css (Cascading Style Sheet) .js (JavaScript file)
The most important of these are the graphic files because the tools you use for your graphics may automatically save them with different filenames than those that can be used for the Web. For example, Adobe Photoshop automatically saves files as .psd files, and Adobe Illustrator saves its files in .ai format. Neither graphic file format can be used with Web pages. However, most graphic creation tools will save the files as .jpg, .gif, or .png if you use Save As instead of just plain Save. When you use Save As, you can select from an available list of file types on most tools, including text editors, word processors, and graphic drawing tools.
1. Open the Control Panel. 2. Choose Appearance and Personalization Folder Options Show Hidden Files and
Folders.
3. Uncheck Hide Extensions for Known File Types (see the gure).
29
Unchecking the Hide Extensions for Known File Types check box in Windows.
Now youll be able to see all your le extensions. So, when you want to load a graphic le, youll know whether its a .png, .jpg, or .gif le just by looking at the lename displayed on your computer screen.
1. Open TextEdit. 2. In the TextEdit menu at the top of the screen, choose Preferences.
The Preferences dialog box appears.
30
CHAPTER 2:UNDERSTANDING HTML5 TAGS LEARNING WHICH FILES WORK WITH THE WEB
If youre new to writing Web pages, the first thing to learn is what files work with Web pages. Directly, HTML5 recognizes, the .html extension and the three graphic file extensions discussed earlier (.jpg, .png, and .gif). However, youll see a reference to .css files. These are external CSS files, whether CSS3 or older versions. Likewise, JavaScript files are saved with a .js extension, and they, too, may have a link reference. The browsers that parse HTML also parse CSS and JavaScript. In fact, you can have HTML files with CSS and JavaScript code written right in with the HTML tags. Whenever you see the <script> tag, youll find either a JavaScript or CSS script in the script container (between the opening <script> and closing </script> tags). At other times, the developer chooses to put all the CSS and JavaScript code in external files and load them using the <link> tag for CSS and the <script> tag for JavaScript. For example, the following code loads the external .css file lookingGood.css:
<link rel=stylesheet type=text/css href=lookingGood.css />
With JavaScript, the external .js file is called from within the <script> container rather than inside of a <link> tag. The following loads a JavaScript file named doMagic.js:
<script language=JavaScript src=doMagic.js />
31 This book concentrates on HTML5, but you definitely need CSS3 for formatting, so youll see it here a good deal, too. For the most part, youll see CSS embedded in the HTML code. In Chapter 3, you learn more about using CSS3 with HTML5. Chapter 12 provides you with a little JavaScript to use with HTML5 tags, and there youll see exactly how to create and use JavaScript with HTML5.
PART I:THE LANGUAGE OF THE WEB STARTING OFF WITH THE BASIC HTML TAG
If youre familiar with HTML4 and describing the document type, you know that you can add a great deal of detail to tell the browser whats up with your page. So, the first tag that you need to consider is not really an HTML tag but instead a tag that communicates with the browser to tell it that youre writing HTML5 and not one of the many versions of HTML4 or XHTML. Here it is:
<!DOCTYPE HTML>
Thats it! Nothing fancy, it just announces to the browser, You can expect an HTML5 document type. Every Web page you make should begin with that tag, and you do not need a closing tag. The exclamation mark (!) tells you its not an HTML tag, but something a little different.
32
That title appears on the pages Windows and tabs. If you dont put it in, youll end up with a blank or default title. Figure 2-1 shows how the title appears in different browsers. As you can see, the title Seriously Sweet Page appears in different places on the four main browsers. On some, it appears at the top of the window and the tab, only at the top of the page, and only on the tab. This helps the user find your page when multiple pages are open simultaneously or simply reminds the user which page hes viewing. Lots of other content goes in the <head> container, such as CSS and JavaScript, but for now, just remember to include a title. Moving right along, the <body> tag demarcates the beginning of the pages content. As the name implies, the body is the main part of any Web page, and only content inside the <body> container is visible on the page. Between the opening and closing body elements, you put everything you want on your page. The following set of tags should go on every page you create in fact, you might as well use it as a template and save it somewhere so you dont have to start off with an empty page to code.
33
As you proceed in this book, youll find more and more structural elements to include. However, the preceding few lines will get you off and running with your Web pages.
Element: The name Attribute: Some characteristic of the element Values: A state or condition of the attribute
Element name
Value (English)
The number of attributes is different for different elements. Depending on the element, different kinds of attributes will be available, and depending on the attribute, different types of values can be applied. As a general rule of thumb, use quotation marks around values, including around numbers. Here are some different examples:
<form action=http://localhost/php/phpversion.php method=post> <input type=text width=120 hidden=false> <input type=submit value=Sick em>
34
You have to be careful about what you put in between the double quotes. For example, value=Sick em is permissible because em has a single quote mark. However, the value Sick em, he said would not work because two pairs of double quotes are included.
Arabic: ar Chinese (Mandarin): cmn German (Deutsch): de Hebrew: he Hindi: hi Japanese: ja Portuguese: pt Russian: ru Spanish: es
Unlike some attributes, the lang attribute has a wide range of values. Go to www.iana.org/ assignments/language-subtag-registry for the full list.
In the <p> container, the double quotes identify the name of a poem. If the same text is to be set off as a poem in a value for an attribute, you can use only single quotes for the name of the poem, as shown in the value assigned to the value attribute. Figure 2-3 shows what the page looks like in a browser.
35
When assigning values to attributes, remember to stick with double quotes for the entire value and use single quotes for highlighting sections within the value. By and large, life will be easier if you avoid using single quote marks when assigning values to attributes.
36
As you can see when you load the page none of the comments is visible in the browser, but as soon as you go back to work coding the Web page, theyll be there. You can put any kind of text in a comment container and it wont get in the way of what you see. One of the many uses of comment tags is whats called commenting out (using your comment tags to temporarily remove tags that you may want to keep around for later use). So, instead of deleting the tags, all you do is to put comment tags around them, and test your page to see if you like it better without the tags in question. If you think that it looked better in the original, you just remove the comment tags. If the page looks better without the commented-out tags, just remove the tags permanently. For example, suppose, youre wondering whether a page youre preparing for a client looks better or worse with a subheading and footnote. Heres the original code with the subheading:
<!DOCTYPE HTML> <html> <head> <title>Commenting Out</title> </head> <body> <header> <h1>Eat at Joes Restaurant</h1> <h2>*Has passed most health inspections since 2005</h2> </header>
37 After thinking about the design, you suggest to the restaurant owner, who is quite proud of his restaurants record, that maybe the message might be better received if the subheading and footnote were removed. However, instead of removing the tags completely, you just comment them out, as the following code (CommentOutCode.html in this chapters folder at www. wiley.com/go/smashinghtml5) shows:
<!DOCTYPE HTML> <html> <head> <title>Commenting Out</title> </head> <body> <header> <h1>Eat at Joes Restaurant</h1> <!-- <h2>*Has passed most health inspections since 2005</h2> --> </header> <section> Joes has the best food on the block! The food is good, cheap, and tastes great! </section> <footer> <!-- <h6>*Little boo-boo in 2010</h6> --> </footer> </body> </html>
Once youve made the changes by commenting out the unwanted tags, you display it to your client again, as shown in Figure 2-5.
38
If the client likes the original better, all you have to do is remove the comment tags, and the page will look like it did before. You may want to experiment with several different appearances; by using the comment tag, you can quickly change it while keeping the original tags theyre just commented out.
NESTING TAGS
When you create an HTML page, you may nest tags you can place one HTML5 container within another container. In fact, Ive been doing that all along. The rule is: Add an end tag inside of a container before the containers end tag. So, if youre writing a tag within another tags container, be sure to close the inside container before closing the outside container. Look at the following examples to see what I mean.
Here, the <body> tag closes outside the <html> container. The <h3> container is correct.
<html> <body>Really interesting stuff <h3>Dont forget to vote!</h3> </html> </body>
39
Here, the <header> tag closes before the <nav> tag does:
<header> <nav> <a href=html5.org>HTML5</a> | <a href=css3.org>CSS3</a>> | <a href=php.net>PHP</a> </header> <footer> <a href=html5.org>HTML5</a> | <a href=css3.org>CSS3</a>> | <a href=php.net>PHP</a> </nav> </footer>
Instead, use two <nav> container sets one for the header and one for the footer:
<header> <nav> <a href=html5.org>HTML5</a> |
Sometimes, when you test your HTML5 page, you wont see what you expect or even anything at all. The first thing you need to check is your tag nesting. In case youre wondering about the code, its a non-breaking space. (The semicolon is part of the tag.) Simply think of it as a space around the vertical bar character (|) used to separate the links. In your browser, youll see: HTML5 | CSS3 | PHP When you place your navigation code inside of <nav> tags, you can easily spot it as navigation. However, like all other tags, you have to pay attention to the nesting conventions used in HTML5.
40
<html lang=
41
<h5>Not responsible for my tastes.<br/> Take it or leave it.< </footer> </body> </html>
This exercise should help you pay attention to the little details. Of all of the gotchas, its the little things that slip under the radar.
SMASHING HTML5
A WEB PAGE is unlike the kind of page you put in your word processor and start typing. Web pages are designed for computer screens of some sort whether its a big desktop, a laptop, or even a mobile device. Youre not dealing with an
CHAPTER
THE FUNDAMENTALS
Before we get going on dealing with text on a Web page, we need to consider the fundamental elements of a Web page. They include three types of actions:
To display text, all you need to do is type it on the page in the <body> container. You can style it with the <h> tag as you know from previous chapters, but basic text requires only that it be in the body of a page. Loading and displaying graphics uses the <img> tag with the following format:
<img src=imageName.png>
You can use only .jpg, .png, or .gif files with the img element. The src attribute refers to the source of the graphic. The img element has other attributes, but all you need to get an image on the page is the src attribute so that the file can be located. Throughout the book, the term URL is often used to refer to a files location no matter what type of file is involved. URL stands for Uniform Resource Locator and refers to a standard protocol for finding and using different types of files. Finally, a link to another page uses the following format:
<a href=anotherPage.html>Link abel</a>
44
The href refers to the linked pages hypertext reference, or more simply put, its address. Like an images source locations, youll see the term url used for a linked pages address as well. One more thing you need to know before continuing. The document type declaration (<!DOCTYPE HTML>) in the very first line is important dont ever leave it out. However, an equally important line is declaring the character encoding. This is used to tell the Web browser which character set of letters to use, such as the A to Z alphabet, Hebrew characters, Japanese, Cryllic, or some other set. You can do it in several ways, but this book uses the following code:
<meta http-equiv=Content-Type content=text/html; charset=UTF-8>
You always should specify character encoding. Although using the <meta> tag is a bit long, you can just cut and paste it in all your Web pages. If you dont, you can run into security vulnerabilities, and nobody wants that.
As you can see in Figure 3-1, everything is jumbled. The image appears right in the middle of the link (blue underlined text), the image appears right in the middle of the page, and generally it doesnt make much sense.
45
When youre organizing a Web page, the links should be organized into a navigation system thats easy for those looking at your Web page to use. In the page shown in Figure 3-1, the link is broken up by the graphic and seems to be part of the text rather than part of a navigation system.
<br>: Generates a single-space line break <wbr>: Generates a line break opportunity
If the link name is not broken up, and if the page is compressed, youll see a big gap in the text or the word broken where you dont want it to be. The <wbr> tag helps you keep your text broken where you want it. Consider the following script (BasicBreaks.html in this chapters folder at www.wiley.com/go/smashinghtml5), which uses both of the line-breaking tags:
<!DOCTYPE HTML> <html> <head> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>Adding ine Breaks and ine Break Opportunities</title> </head> <body>
46
<img src=logo.png><br> This is text. You dont need a tag for Plain Old Text (POT).<br> <br> He said, Sometimes you have extremely long words, and you want to make sure that they break at appropriate places. For example, you have a long name for a URL like www.eat<wbr>at<wbr>joes<wbr>fine<wbr>restaurant<wbr>.com, and if it has to break, you want the break to appear in a particular place.<br><br> He said, Sometimes you have extremely long words, and you want to make sure that they break at appropriate places. For example, you have a long name for a URL like www.eatatjoesfinerestaurant.com, and if it has to break, you want the break to appear in a particular place.<br><br> <a href=anotherPage.html> Click here for another page </a> </body> </html>
By adding the two line-break tags, the page looks much better. The paragraph that does not use the <wbr> tag has a big gap in it where the long URL was not divided up into sensible break points. Figure 3-2 shows how the page now appears. Although its still not perfect, its a lot better than the original, even though two more paragraphs were added. The graphic is in the upper-left corner (as most logos are), the paragraphs are separated by line breaks, and in the first paragraph using the long URL, the breaks are where the <wbr> tag specified.
47
Logo Navigation
Graphic
xxx
xxx xxx
xxx Heading
Text
xxx
xxx
xxx
Navigation
You may have noticed that the alt attribute was also included. That attribute lets users know what to expect if the image takes a while to load. So, now, with just a few tags and an added attribute, this next script does a fair job of creating the page with the structure in the sketch in Figure 3-3. As youll see in the following code (Sketch2Web.html in this chapters folder at www. wiley.com/go/smashinghtml5), Ive used a pound sign (#) instead of an actual URL in the navigation links. The pound sign acts as a placeholder while were working on the structure; it works just like a real URL except that it doesnt go anywhere or cause an error message.
<!DOCTYPE HTML> <html> <head> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>Sketch to Web</title>
48
</head> <body> <img src=logo.png alt=logo><br> <a href=#>Toys</a> | <a href=#>Clothes</a> | <a href=#>Sports</a> <br> <br> A Good Place for Kids <br> <br> <img src=kid.png alt=kid align=left> Kids are serious business. They need toys that are both safe and educational. Toys need to be fun and allow childrens minds to create beyond any functionality the toy has. There is no reason that they cannot be both safe and fun. Children need lots of clothes because they grow so fast. And they need sports to offset childhood obesity and the illnesses associated with obesity. <br> <br> <a href=#>Toys</a> | <a href=#>Clothes</a> | <a href=#>Sports</a> </body> </html>
Notice that we didnt use any of the H elements introduced in the previous two chapters. Thats because I cover them in the next section and give you a better sense of their value. Figure 3-4 shows how close the page came to the sketch in Figure 3-3.
49
Figure 3-4: A page with a basic structure.
David Sanders
Now the Web page shown in Figure 3-4 has more structure than any of the previous examples. The navigation bars at the top and bottom are helpful to the user, but perhaps theyd look better centered on the page. Maybe the top navigation bar should be at the very top of the page in the center, right next to the logo. Also, the text is jammed right next to the image and could use some space. Of course, the heading should be in a different style, weight, size, and font. Also, its pretty boring especially since its for kids. However, because the structure is coming along, you can address those other details when you learn to use more styling tools.
50
In terms of organizing your page, the layout for different levels of h elements is the HTML5 <hgroup> tag. For example, take a look at the following Web page (HelementOrg.html in this chapters folder from www.wiley.com/go/smashinghtml5) from Wittgenstein (who seemed to write using h tags in 1918 when he completed writing Tractatus Logico-Philosophicus):
<!DOCTYPE HTML> <html> <head> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>Tractatus logico-Philosophicus</title> </head> <body> <h1>Tractatus logico-Philosophicus</h1> <h1>by Ludwig Wittgenstein</h1> <hgroup> <h2>1 The world is all that is the case.</h2> <h3>1.1 The world is the totality of facts, not of things.</h3> <h4>1.11 The world is determined by the facts, and by their being all the facts.</ h4> <h4>1.12 For the totality of facts determines what is the case, and also whatever is not the case.</h4> <h4>1.13 The facts in logical space are the world.</h4> <h3>1.2 The world divides into facts.</h3> <h4>1.21 Each item can be the case or not the case while everything else remains the same.</h4> </hgroup> </body> </html>
51
If you look at the original Wittgenstein, youll find that his style of writing used an indented outline that appeared as the following: 1 The world is all that is the case. 1.1 The world is the totality of facts, not of things. 1.11 The world is determined by the facts, and by their being all the facts. 1.12 For the totality of facts determines what is the case, and also whatever is not the case. We can fix that if we want by adding indents to the <h..> tags. We could do this by adding margins using CSS3 as youll see in the next section. However, the purpose of the h element and the <hgroup> is not to set indents but to help with more general outlines. The <hgroup> tag sets the highest level <h..> tag in the hgroup container as the outline element. For example, since Wittenstein wrote Tractatus Logico-Philosophicus wholly in outline, his entire work using the hgroup element would look exactly like the outline in his actual Abstract to the work.
You can use the <style> tag to define the properties of elements in the HTML5 page. You can use external style sheets, which are text files where you store a style you may want to reuse.
Most professional developers and designers prefer the CSS3 external style sheets because perfecting the desired style takes a lot of work. When you want to make a change to the design of a Web site, you can make changes to many pages that use an external style sheet, just by changing the one style sheet. Its just more efficient than having to change the <style> attributes in each individual Web page.
53
Each element has a unique set of properties, and each property has values that can be assigned to it. When you change the value of the property, that value appears in the text inside the elements container. So, if you change the text color to red, all the text inside the elements container will be red. The following script (CSS3fonts.html in this chapters folder at www.wiley.com/go/smashinghtml5) provides an example.
<!DOCTYPE HTML> <html> <head> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <style type=text/css> body { background-color:#fbf7e4; font-family:Verdana, Geneva, sans-serif; margin-left:20px; color:#8e001c; } h1 { background-color:#8E001C; color:#e7e8d1;
You should be aware that when you use style sheets, you have to pay attention to the little details like adding both curly braces, separating the property from the values by colons, and ending each property value with a semicolon. If your CSS3 style sheet doesnt work as you think it should, check those little gotchas! When using background colors, the background often extends across the entire page. Certain inline elements such as <span> can be used to contain the background to the affected text. With background colors in headers that are left- or right-justified, youll want to add a space ( ) so that it doesnt bleed into the background color of the page.
The background color must be #F2CC6E. You dont have to know what the color is you just have to know that the company has decided that its going to be the background color. Youre told that the designers can figure out the rest. Further, youre told that theyd like a version that looks good on a phone and a different one that looks good on a desktop. So, that means youre going to need two different CSS3 style sheets. Later on, youll worry about how the browser is going to know whether the user is viewing from a desktop with a screen the size of a drive-in theater or viewing from a Droid phone. 55 All thats required is the following tag:
<link rel=stylesheet type=text/css href=mightySmiteSmall.css />
This tag goes in the <head> container where the <style> tag had gone along with the CSS3 code. Now the CSS3 code goes into a separate file. Notice that the <link> tag contains an href attribute assigned the value mightySmiteSmall.css. Thats the name of the CSS3 file in this chapters folder at www.wiley.com/go/smashinghtml5. The Small indicates that its designed for mobile devices. Another CSS3 file will be created called mightySmiteLarge.css for non-mobile devices. To create a CSS3 file, all you have to do is enter the CSS3 code in a text editor or Web development application minus the <style> tags. The following shows the example to be used here:
@charset UTF-8; /* CSS Document */ /*3C371E,8C5F26,BCA55F,F2CC6E,F26205 */ body { background-color:#F2CC6E; font-family:Lucida Sans Unicode, Lucida Grande, sans-serif; color:#8C5F26; font-size:11px; max-width:480px;
The top line lets the browser know that its a UTF-8 character set, and the second two lines are comment lines. Theyre different from the comment lines in HTML5, but they work the same. The second comment line is a handy way to keep track of the color palette and can save time in setting up the style sheet. 56 To test this mobile version of the CSS3 code, the following HTML5 file (ExternalSmall. html in this chapters folder at www.wiley.com/go/smashinghtml5) is used:
<!DOCTYPE HTML> <html> <head> <link rel=stylesheet type=text/css href=mightySmiteSmall.css /> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>Mighty Smite Sofware Test Sheet</title> </head> <body> <h1>Mighty Smite Software Conglomorate</h1> <h2>This is an h2 head</h2> <h3>Heres an h3 head</h3> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut abore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco aboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est aborum. </body> </html>
All the styles in the CSS3 file are used to test their appearance, and the body text beginning with Lorem ipsum is filler text, used to get an idea of what a text block looks like. (Its been used since the 16th century, so it must be good.)
57
58
A unique feature of many mobile devices is that they allow Web pages to be viewed from different aspects vertical or horizontal. So, when Im preparing a CSS3 file for a mobile device, I tend to set the width to the horizontal. However, youll quickly find that different mobile browsers work differently. At the time of this writing, the Apple Safari browser on the iPhone displayed the page in a tiny, unreadable page that had to be expanded, but the Opera Mini browser (as shown in Figures 3-9 and 3-10) on the same iPhone using the same size screen displayed the page immediately in an optimum viewing size, whether viewed horizontally or vertically.
Inline style
A third way to add CSS3 to your document is to simply add a style attribute to an element that redefines the content in the elements container. For example, the following code (InlineCSS3.html in this chapters folder at www.wiley.com/go/smashinghtml5) has style changes in the <div> container and the second <p> container:
<!DOCTYPE HTML> <html> <head> <meta http-equiv=Content-Type content=text/html; charset=UTF-8>
Figure 3-11 shows what you see when you test the Web page in a browser. Keep in mind that the second line has no styling at all added.
59
The use of inline CSS3 can be invaluable when some feature of your CSS3 external file doesnt have a style for something on your Web page that needs to be there. Generally, inline is one of those tools you want to use both sparingly and judiciously. This is especially true when dealing with other developers and designers who are working from a common style sheet.
CSS3 classes
You create style classes in an almost identical way as you do element styles. The dot (.) definitions used to create a class in CSS3 are labels you make up instead of using element names. Figure 3-12 shows how to create a CSS3 class definition.
As you can see, the dot definition goes where the element name goes. The rest is identical to CSS3 definitions for elements. However, implementing a class style is a bit different because it can be used in almost any element tag. In order to see how we might want to use a bit of highlighted text, a very handy inline element is span. The <span> tag can be added in the middle of a block element and only change that part of the content in the span container without changing the rest of the block. To add a class to an element, you use the following format:
<element class=myClass>
60
Notice that the name of the class does not include the dot from the dot definition. The dot is used only in the style definition to let the parser know that the word is a class and not an element. The following program (SpanClass.html in this chapters folder at www.wiley. com/go/smashinghtml5) gives you an example of how you might use the class with the <span> tag.
<!DOCTYPE HTML> <html> <head> <style type=text/css> body { background-color:#F93; } .highlight { background-color:yellow; } div { font-family:Comic Sans MS, cursive; font-size:18px; } h1 { font-family:Arial Black, Gadget, sans-serif; color:#930; text-align:center; font-size:20px; } </style>
When you test the program, youll see that the two portions of the text within the <span> containers are affected. Figure 3-13 shows how theyre displayed in a Chrome browser on a Mac (top) and an Opera Mini browser on an iPhone (bottom).
Mobile phone
61
Desktop computer
Figure 3-13: Class dened style in <span> container on desktop computer (top) and mobile device (bottom).
Both displays clearly show that the CSS3 class named highlight is working fine. However, the Opera Mini browser displays neither the defined fonts nor the italicized words. (The Safari browser does display the italicized words, but not the defined fonts.)
CSS3 IDs
A CSS3 ID is set up almost exactly like a class except that it uses a pound sign (#) instead of a dot (.) in the definition. Further, in assigning an ID, you use ID instead of class to specify which ID to use with an element. You even can use IDs and classes with the same element. The following tag is perfectly correct:
<p ID=this class=that>
Both can select styles, and the ID provides a unique ID for the paragraph. The ID has some major differences from a class. Both a class and an ID can be used as style sheet selectors. However, an ID has some other limitations and features:
An ID can be used only once in a document. An ID can serve as an anchor (see Chapter 7). An ID can act as a script reference. Thats important for JavaScript. An ID can be used as a name in a declared object element more stuff from JavaScript. An ID can be used by agents for processing information in translating an HTML document.
62
Of these features, youll be using only the first two until you decide to incorporate JavaScript and other languages into your rsum. Nevertheless, if you pay attention to these differences, your Web pages wont run into problems later on (and others will think youre a pro). The following example (IDwork.html in this chapters folder at www.wiley.com/go/ smashinghtml5) shows a use of the ID with CSS3:
<!DOCTYPE HTML> <html> <head> <style type=text/css> #littleHead { font-family:Verdana, Geneva, sans-serif; background-color:#9FC; font-size:16px; } #javascript { /* red */ color:#cc0000; } #php { /* blue */ color:#009; } #actionscript { /* green */ color:#063; }
In looking at that code, you may have wondered what the slash-asterisk (/* ... */) marks are. Quite simply, theyre comment code for CSS3. Within a <style> container and in external style sheets, they work just like the <!-- --> comment marks in HTML5. Figure 3-14 shows what youll see when you test it.
63
If you have a long Web page with discussions about JavaScript, PHP, and ActionScript, the user may have to scroll down to find the topic he wants. Using IDs, you can write the URL to include the exact paragraph the user is trying to find. For example, the following URL will go directly to the paragraph covering PHP: www.smashingHTML5.com/myIDs#php. The added #php calls the specific paragraph with the php ID.
You can design better than that! After starting a Web page using different h elements, the page that resulted in what you see in Figure 3-4 still needs help. For a kids page, its not too colorful and the font is boring. Besides, the text is right next to the image. Using CSS3, see if you can make it better.
Help poor Wittenstein! After ducking bullets in World War I while preparing Tractatus Logico-Philosophicus, our Web page in Figure 3-6 shows Wittensteins work without the indents! However, using CSS3 and the margin-left property, see if you can fix those h elements so that all the elements are there. By the way, if you want all 29 pages of Tractatus Logico-Philosophicus, you can download it for free at http://filepedia.org/ tractatus-logico-philosophicus.
Have some fun with this and see the flexibility that CSS3 gives you.
64
SMASHING HTML5
UP TO THIS point, youve seen several examples of using color codes, but unless you understand what youre looking at, you may as well be looking at the enigma code. In some examples,
CHAPTER
USING NAMES
One of the stranger experiences in working with HTML5 and CSS3 is the name set used with colors. At the root are the 16 standard colors shown in Table 4.1.
Table 4.1
Aqua
66
Using the HTML5 that youve learned so far, you can easily create a chart showing all the colors. (In the Take the Wheel section at the end of this chapter, youll work out how to re-create the table.) Figure 4-1 shows what they look like on a Web page on a mobile device.
From this root base, you can include another 131 names that seem to have no rhyme or reason in terms of why they were selected. Theyre all part of a set created back in the 1980s called X11. They were adopted in the early browsers and have been with us ever since. In the official W3C documentation, theyre listed under Scalable Vector Graphics (SVG), and all the
The reason that all the names havent been listed here is because designers and developers generally dont use them. For designers, not only do the 131 names severely limit their palette, but the ones selected are nuts! Colors like papayawhip and mistyrose are hardly standard names for artists. Likewise, for developers, the values used dont conform to any mathematical set such as the old Web-safe colors that follow a logical numeric standard. (Of course, if you want to have some fun, go ahead and include darkkhaki and ghostwhite in your Web pages color palette.) In the next sections, youll see how to create the exact color you want from over a million possible combinations.
The first value is the percent red; the second, green; and the third, blue. For example, the setting, rgb(43.9%,50.2%,56.5%) generates the color that the Los Angeles Dodgers use. The three percentage values add up to more than 100 percent, so you know that the percentage is a percent of the color itself and not the total. As you can see, you can be very precise for values, including fractions of percentages. The following script (RGBpercent.html in this chapters folder at www.wiley.com/go/smashinghtml5) shows how to use this color assignment in an HTML5 page:
<!DOCTYPE HTML> <html> <head> <style type=text/css> body { background-color:rgb(43.9%,50.2%,56.5%); } h1 { background-color:rgb(11.8%,56.5%,100%); color:rgb(100%,100%,100%); font-family:Arial Black, Gadget, sans-serif; font-style:italic; text-align:center; } </style> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>Dodger Blue</title> </head> <body>
67
When you launch the page, the colors come out precisely as you instructed, as shown in Figure 4-2.
68
A second way to assign colors using percentages is to use a hue-saturation-light (HSL) model. The big advantage of HSL is that lightness is symmetrical. That makes it easier to tweak a color to what youd like it to be. By thinking of a color circle arranged around 360 degrees like a compass, you select a hue. At the top, or 0 percent, you find the reds. Moving clockwise, at 30 percent the hues turn red-yellow. At 60 percent, theyre yellow. And so on around the color spectrum until youre at 360 percent (0 percent) where youre back to the red hues. For designers who understand the color spectrum, this makes choosing colors much easier. To create a lighter color, increase the light value; decrease the light value to make the color darker. For example, suppose youre trying to get just the right shade of red. You start with the following color assignment:
hsl(0,100%,50%);
Notice that the first value is not a percentage. Thats because it has values between 0 and 359 the 360 degrees of a circle. (Remember: 0 and 360 are the same point on the circle.) By raising and lowering the light (the third parameter), you can make your color lighter or darker which is far more intuitive than changing RGB percentages. The following HTML5/CSS3 script (HSLColor.html in this chapters folder at www.wiley.com/go/ smashinghtml5) shows how easy it is to lower and raise the light value to get just the right shade of red.
<!DOCTYPE HTML> <html> <head>
When first using HSL, it helps to think of adding light by going higher to the sun or making it darker by going lower into a well. The tweaking process is easier for designers to get just what they want. Figure 4-3 shows what the different red tints look like. 69
Hue and light are fairly intuitive to understand, but saturation can be a little murky. Essentially, saturation is the amount of colorfulness in a given color. A 100 percent saturation is the full colorfulness of a hue in a given light, while a lower percent subtracts from a hue something like a color fading. For all colors, a midpoint light is going to be gray when saturation is 0 percent. Sometimes a faded or muted color is preferred, like blue jeans that have been washed many times.
Its not as intuitive as HSL, but after a while, you start getting a sense of mixes based on 256 values rather than percentages. The following example (DecColor.html in this chapters folder at www.wiley.com/go/smashinghtml5) shows a simple implementation.
<!DOCTYPE HTML> <html>
70
<head> <style type=text/css> body { /* Red background */ background-color:rgb(255,0,0); } h1 { /* Big Yellow Text */ color:rgb(255,255,0); font-family:Arial Black, Gadget, sans-serif; } h2 { /*Blue Text + Gray Background */ color:rgb(0,0,255); background-color:rgb(150,150,150); } </style> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>Decimal Colors</title> </head> <body> <h1> Big Yellow Header</h1> <h2> Blue header with a gray background</h2> </body> </html>
Figure 4-4: Colors mixed using integer values, shown on a mobile device.
As you can see in Figure 4-4, the mobile device is not picking up the Arial Black font, but it has no problems with the colors. Be sure to check your mobile device for fonts and other effects if theyre essential to how your page looks. Remember: Most computers have a far more complete set of fonts and styles than mobile devices do. In time, though, they should be very similar.
71
Numbering Systems
Decimal
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Hexadecimal
0 1 2 3 4 5 6 7 8 9 A B C D E F
72
1110 1111
Each of the binary values is called a bit. A group of bits is called a byte. In Table 4.2, the largest binary value is a 4-bit byte. Computers are arranged in different types of bytes, and the 8-bit byte is commonly used as a general reference to a byte. However, modern computers are actually organized into 8-, 16-, 32-, 64-, and even 128-bit bytes. (They just keep getting bigger, so dont expect 128-bit bytes to be the top limit.) The highest value for a binary counting system in an 8-bit byte is 11111111. When you look at that compared with decimal and hexadecimal numbers, you see a very interesting pattern, as shown in Table 4.3.
Table 4.3
Binary
11111111
Byte Values
Decimal
255
Hexidecimal
FF
As you can see in Table 4-3, the hexadecimal value FF is the highest possible value for two digits; similarly, the binary value 11111111 is the highest possible value for eight digits (a byte). However, the decimal number is three digits and does not represent a limit for those digits. In other words, the decimal system isnt very symmetrical with the binary counting system, but the hexadecimal system is.
73
This example uses a color palette and simply places the color values in a comment within the <style> container so that it can be viewed while putting the Web page together. Figure 4-5 shows what you can expect to see.
74
The colors belong to a set of colors that create a certain mood or feeling. This one, Desert in the Fall was based on what the designer believed to be a palette representing that time of year in the desert.
75
The results shown in Figure 4-6 are shown on an iPhone and they look no different than what youll see on your a computer screen. As you can see, the transparent text and background allow the background object to show through. When a color is transparent, it picks up some of the underlying color; so, when you use it, bear in mind what the combination of the underlying and overlying colors look like together. (By the way, Figure 4-6 shows why you rarely want to use background images they have a way of cluttering the screen and destroying any sensibility in the text.)
76
FROM AN IMAGE
In addition to creating a color palette from a base color, you also can load an image, and Kuler automatically generates a color scheme based on the images color. For example, Figure 4-8 shows two different images a logo and a painting with their respective color palettes.
77
78
When using an image, you can further modify the color scheme by selecting from several moods colorful, bright, muted, deep, and dark. All color schemes can be saved and when loaded, they maintain all the information you need for entering color data into an HTML5 Web page.
The hexadecimal integer values for the four colors are pasted right in with the CSS3 at the top of the HTML5 page for reference. The following script (ColorsPhoto.html in this chapters folder at www.wiley.com/go/smashinghtml5) employs the colors so that they work with the logo and rest of the page.
<!DOCTYPE HTML> <html> <head> <style type=text/css> /* 027333,7FA646,D9B448,F2DFA7 */ body { margin-left:1em; background-color:#F2DFA7; color:#027333; font-family:Verdana, Geneva, sans-serif; font-size:11px; } h1 { font-family:Tahoma, Geneva, sans-serif; color:#7FA646; } h2 { font-family:Lucida Sans Unicode, Lucida Grande, sans-serif; color:#7FA646; background-color:#D9B448; } div { text-align:center; } a { font-family:Arial, Helvetica, sans-serif; text-align:center; font-size:10px; text-decoration:none; background-color:#027333; color:#F2DFA7; } a:hover { color:#D9B448;
79
80
The CSS3 script uses the property a:hover to change the property when the mouse is over the link. In the <a> tag CSS3 definition, the text-decoration is set to none, which means that the text link will not be underlined. Without the underline, you want to do something to alert the user to the presence of a link; you do that using the hover property. Changing the color of the link text subtly yet effectively shows the user that the mouse is over the link. Both the initial color and the hover color are part of the palette. So, in setting up the page, remember that more than just the <body> and <h> tags use the color palette. This particular design is focused on mobile devices (see the right side of Figure 4-10), but it should work with computer and table screen as well (see the left side of Figure 4-10). Of course, your page is always going to look better if you have a Web designer do the page design. However, even developers can make it look better by paying attention to the color combinations.
81
Reproducing the standard color chart: In Figure 4-1 is an image with the standard colors. Your first challenge is to see if you can reproduce the Web page that displays those colors. Here are a couple hints to get started: Define each named color as a class in your <style> container with the same color for the text and background colors.
.aqua { color:aqua; background-color:aqua; }
One way to do this is to use the <span> tag to assign classes to the content of the
<span> container.
<h3> <span class=aqua>COLORNAME</span><span class=black>COLORNAME </span><span class=blue>COLORNAME</span><span class=fuchsia>COLORNAME </span> <h3>
Your picture belongs on a Web page! This is a three-part task: 1. Make a digital image of yourself using the built-in camera on your computer or upload one from a digital camera. 2. Load the image into Kuler and create a color palette. 3. Create a Web page with your picture using the color palette you created in Kuler.
II
Chapter 5: Organizing a Page Chapter 6: Displaying Data with Tables Chapter 7: All about Links Chapter 8: Navigation Strategies
PART
II
SMASHING HTML5
ORGANIZING A PAGE
organizational elements become clear only once you start using JavaScript, but if you set up your page according to HTML5 guidelines, your page will be good to go when you start adding a little JavaScript.
MANY OF THE new tags in HTML5 are organizational tags. In previous chapters some have been used but not really explained. This chapter looks closely at organizing HTML5 pages with the help of CSS3 and a way of understanding this organizational process. Some of the
CHAPTER
86
The <html> tag is the root element, and within that element, you can include a language attribute. Then within the <head> container are metadata elements. Also in the <head> container are the scripting elements; they, too, are briefly covered in this section and expanded upon in Part IV of this book. Other than the CSS3 scripts, the examples so far have not put a lot of tags into the head of the HTML5 document. The <meta> tag has many uses, but so far, weve used it only to specify the character set. This chapter shows more uses for the <meta> tag.
87
What is happening here? The <base> tag is telling your browser how to resolve any references to other documents in your HTML such as the <a href=Base.html> anchor tag. Your browser will know to look for the Base.html document in the location specified in the <base> tag; namely, http://www.sandlight.com/html5/smashing/.
Each of the content values must be separated by a comma. These tokens can be directly related to your content or what someone might look for. Content meta tags are easy to set and you can help users find their way to your site.
For example, the following tag refreshes (reloads) the page every 30 seconds:
<meta http-equiv=Refresh content=30>
Not only can you reload the same page, but you can reload different pages. If you want to load a sequence of pages, you can set the initial meta tag set as follows, to set the page assigned as a URL value after 12 second:
<meta http-equiv=Refresh content=.5; URL=pg2.html>
Notice how the content value of both the number of seconds and the URL are in the same set of quotation marks. The following HTML5 code launches a series of pages that keep refreshing until a home page is loaded:
<!DOCTYPE HTML> <html>
88
<head> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <meta http-equiv=Refresh content=.5; URL=pg2.html> <title>Image 1</title> </head> <body> <img src=one.png alt=one> </body> </html>
After the initial page, you would have the following sequence only one per page:
http-equiv=Refresh content=.5; URL=pg3.html> http-equiv=Refresh content=.5; URL=pg4.html> http-equiv=Refresh content=.5; URL=pg5.html> http-equiv=Refresh content=.5; URL=homeNow.
The home page, homeNow.html, would have no Refresh state in the <meta> tag. In fact, other than the meta element with the Content-Type, it would have no other meta tag. (This thing would go on forever if you looped the home page back to the first page!)
The JavaScript program goes into the remainder of the <script> container. The following HTML5 code (ScriptTag.html in this chapters folder at www.wiley.com/go/ smashinghtml5) shows how easy JavaScript is to learn.
<!DOCTYPE HTML> <html> <head> <script type=text/javascript> alert(I can do JavaScript!); </script> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>A Taste of JavaScript</title> </head> <body> A regular Web page.... </body> </html>
89
When you test that little program, youll see an alert box pop up (shown in Figure 5-2).
As a side note, youll see that the JavaScript alert window is loaded before your Web page loads. Thats because everything in the head container loads first. If you have a more elaborate JavaScript program that will be used in your HTML5 page, youll want to test it on different browsers and also put it in an external JavaScript file. Figure 5-3 shows the same alert window in Safari on an iPhone; you can clearly see that the Web page associated with the HTML5 code has not loaded.
90
As with style sheets, JavaScript programs can be loaded from external files. However, instead of using the link element, the JavaScript files are loaded using the script element, as the following example shows:
<script type=text/javascript src=smashingJS.js></script>
The JavaScript file is saved using the .js extension, just as CSS3 files are saved using the .css extension. Youll see JavaScript is employed a good deal when using the <canvas> tag and several other HTML5 tags in Part IV of this book. Further, <script> tags and the JavaScript code in them can be added right in the middle of an HTML5 script. The advantage of placing your JavaScript in the head container, though, is that its loaded first, before the Web page.
A DESIGN IN SECTIONS
One of the major changes in HTML5 compared with older HTML versions is in the sections. Prior to HTML5, you could pretty well think of sections in terms of the body element and some <h> tags. In HTML5, a page can be envisioned in terms of a number of sections with subsections. A larger context in a Web page is an article, and just like an article in a magazine, you can find different sections that constitute the building blocks of the article. Figure 5-4 provides an overview of the sections in an HTML5 page.
91
In looking at Figure 5-4, you can see different blocks of information, but the tags used generally dont have any inherent capacity to structure the information visually. The <h> tags, which are section elements, certainly configure text to different sizes. However, the other section tags are as much for helping to organize a page as they are for specifying the visual display of the page. The section elements include the following:
The body element is the sectioning root just as the html element is the page root. Throughout the previous chapters, youve seen several of the section elements, so youre familiar with them. However, a script helps to see how theyre used in conjunction and consider their uses (ArticleStructure.html in this chapters folder at www.wiley.com/go/ smashinghtml5).
<!DOCTYPE HTML> <html> <head> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>Sections</title> </head> <body> <article> <header> <h1>Pilots and Planes</h1> <p><q>I never left one up there. </q><i>Ace Davis</i></p> </header> <nav><a href=#> Safety</a> | <a href=#>Check Lists</a> | <a href=#>Landings</a></nav> <section> <h2>Flying Stories by Real Pilots</h2> <h3>...and other cures for insomnia.</h3> <section> <h4>Short Final</h4> <p>As we were on short final, control cleared the Maule for immediate takeoff, which it did in about 15 feet of runway at an airspeed of 20 mph. It filled my windshield as I approached stall speed. After realizing its mistake, the tower instructed the Maule to loop, and we were able to land without incident.</p> </section> <section> <h4>Thermal on Takeoff</h4> <p>Taking off from Gila Bend, Arizona, with the ambient temperature of 130 F, we encountered a strong thermal at the end of the runway, which took our Cessna 177b to 15,000 feet in 12 seconds flat, at which time we leveled off and proceeded to New Mexico via the jet stream, setting a new speed record.</p> </section> </section> <aside> <h2>Truthful Pilot Found!</h2> <p>Emily Rudders, a pilot in Moose Bite, Vermont, was recently found to be the only truthful pilot in existence. When asked to relate her most exciting flying adventure, Emily replied, <q>I aint never flew no airplane. I jus shoot at em when they fly over and bother the moose.</q></p> </aside> <footer>
92
<address>
The purpose of sections is to divide the page into coherent parts. Theyre an organizational set of elements, and while they can be used for formatting, that isnt their main purpose. For adding formatting to a paragraph or group of paragraphs, the W3C Standards encourage the use of the <div> tag. Figure 5-5 shows what the page looks like. Although it isnt an attractive design, it is a functional one. The article is about pilots and flying. The articles header announces the topic (pilots and planes) and provides a quote from a pilot using a <q> tag. After the header, the first section is about flying stories. Nested within the first section are two other <section> tags that separate out the two stories. A somewhat related section about the veracity of pilot stories is placed in a separate aside element container. In Figure 5-4, you may have noticed that the aside was placed in a separate column, but in and of itself, an aside element is a reference to the sense of the page. It is not a formatting element as such. 93
Finally, at the bottom of the article is a footer. Footer elements can go anywhere, including inside individual section and aside element containers. Footers act as a closing organizational element for the section elements. Within the footer is an address element with a link to a URL related to the article. In looking at the page in Figure 5-5 and the code, you can see the sense of the page described in the section tags. As noted, theyre really not for formatting but for organizing the sense of the page. 94
That code works perfectly well in HTML5, but its better organized using the most specific element for the job. A better code would look like the following:
<header> <h1>All About Important Stuff</h1> </header> <section> <h2>Finding True Love</h2> <h2>Choosing the Right Career</h2> <h2>Getting a Parking Place</h2> </section>
On your Web page, they look the same, but with HTML5 youll find your pages more sensible using the new section elements. So the question is, Where can the p and div elements be used? Actually, you dont want to rely on either very much. However, when you want to add a style element or some other attribute in the middle of an <article> or <section>, they can be handy. Consider the following (UseDiv.html in this chapters folder at www.wiley.com/go/ smashinghtml5).
<!DOCTYPE HTML> <html> <head> <style type=text/css> body { font-family:Comic Sans MS, cursive; color:#0C6; background-color:#FFC; } .girls { background-color:pink; } .boys { background-color:powderblue; } </style> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>Baby Names</title> </head> <body> <article> <header> <h1>Baby Names</h1> </header> <section>
95
Figure 5-6 shows the output, but the important point is that the <div> tag was employed only to provide the background colors for two different <section> elements. 96
97
As you can see in Figure 5-7, the meaning of the group at the beginning of the World Cup has no hierarchy the list is just four teams at the World Cup. However, at the end, the order means everything, so the ordered list element is more appropriate.
98
You may also note that the two different kinds of lists have different background colors added with CSS3. So when using grouping elements, you might also want to further group the content using color, as shown in both Figures 5-6 and 5-7.
99
100
As you can see, the <hr> tags are all within the article element, while the title is part of the header element. However, in Figure 5-8, the page is shown in a mobile device, and the horizontal rules do nothing to clarify and everything to fragment. Where your page has a major division, a horizontal rule may be appropriate. However, even then you should add CSS3 to lighten the hr element so that its subtle even adding transparency will help. Good designers know how to use horizontal rules sparingly and subtly, but non-designers can easily make a mess of their Web pages with overuse of <hr> tags.
101
In more sophisticated CSS3 formatting, the figure and its caption can be treated as an object with a parent-child relationship. Just because figure and figcaption are part of HTML5s grouping elements that doesnt mean theyre formatted on the page together; instead, it means that they can be referenced as a single flow in the main content of the page. In the meantime, youll have to carefully work with the two elements together, as shown in the following HTML5 program (Figure_n_caption.html in this chapters folder at www.wiley. com/go/smashinghtml5) where the caption references a stylized image.
<!DOCTYPE HTML> <html> <head> <style type=text/css> /* 732D3F,A66879,D9C3B0,260101,F2F2F2 */ body { background-color:#D9C3B0; color:#732D3F;
102
You can begin to think about elements and their descendants. In this case, the figcaption element is a descendant of the figure element. Figure 5-9 shows the caption under the picture, both within the <figure> container. As you can see clearly in Figure 5-9, the <figcaption> is differently styled, even though its a descendant of the <figure> container. However, you cant assume that a figcaption element will be correctly positioned as in Figure 5-9 just because its a child of the figure element that it captions.
103
ORGANIZING FILES
With a simple Web site, the organization of the files is simple. As the complexity of a site grows, especially if multiple designers and developers are involved, you need to get your site organized in separate directories and even servers sometimes. In this section, youll learn about several organizational issues and how to deal with file organization and access.
Formal Classifications (Animals > Mammals > Rodentia > Myomorpha > Mus musculus > Mickey) Topic (Vacations > Where to Go > Where to Stay > What to Pack) Processes (Baking > Making Dough > Preparing Dough > Setting Oven > Timing)
Whatever organizational plan is implemented, you need to understand how to access the images no matter how theyre organized. All references are either to absolute or relative addresses.
ABSOLUTE REFERENCE
Any reference to an image is through a URL, whether its a full listing of the address or one that references just the name of the file. An absolute address begins with http:// and includes the full path to the HTML5 file. For example, the following is an absolute address to a file:
http://www.smashinghtml5.com/organization/graphics/faces.html
No matter where that URL is called from, it recognizes it as the named file at the end of the URL. The same is true with a source (src) reference to an image. If your code has the following link, no matter where the calling Web page is located, it will load nose.png.
<img src=http://www.smashinghtml5.com/organization/graphics/nose.png>
104
The calling Web page could be on an entirely different server, and it would go to the absolute address. The advantage of using absolute addresses is that you dont have to worry about where a page is in your Web site. You dont even have to worry if its on the same server. However, it leaves a good deal to be desired in terms of site organization, and then there are those long URL names you have to get just right.
RELATIVE REFERENCE
A relative reference is relative to the calling pages position on a Web site or its defined base. On your computer, your Web page has a file position rather than an http position. For example, the following is the absolute position on the file somePage.html:
file:///Macintosh HD/Users/billsanders/Desktop/HTML5/somePage.html
If I have a graphic in the folder HTML5/, I can use its relative address to call it from somePage.html. For example, if I have anyGraphic.png in the HTML5 folder I just use the following relative reference:
<img src=anyGraphic.png>
You can drill down as many relative levels as you want with each level separated by a forward slash (/). For example, a more complex graphic set would look like the following:
<img src=images/animals/dogs/greaterSwissMtDogs/myDoggy.png>
Besides drilling down you may also want to drill up. By drilling up, you access resources in folders your calling page is in. For example, suppose you have the following path and your HTML5 page is in the baseFolder.
topFolder/middleFolder/baseFolder
To access a graphic file in the middleFolder, you would use the following format:
<img src=.../anyGraphic.png>
If the graphic were in the topFolder, you would use the following format:
<img src=../../anyGraphic.png>
105 In drilling up, you dont name the target folder your calling Web page is in; instead, you use successive ../ characters until your call is at the level you want. This means, you can drill up to the level you want, and then drill down another branch. For example, the following drills up to the topFolder, and then inside the topFolder drills down through the image folder to the target graphic:
<img src=../../images/anyGraphic.png>
Figure 5-10 provides a general graphic illustration of accessing resources in higher- and lower-level folders.
.../images images
106
Even though the domain for the first page (Earth.html) is smashingHTML5.com, the base is set to smashingHTML5.net. As a result, a relative link to Alien.html, which resides on smashingHTML5.net, is made without having to use an absolute address.
Whats interesting about Muybridge is that, in 1878, he was able to create movies using a series of photographs. So, well before Thomas Edison invented the motion picture, Muybridge was making short movies (about 12 frames) giving us an animated view to the past. The University of California, Riverside, has preserved and animated Muybridges work using animated GIF files online. To see how you can make animations using refresh pages, download one of the animated GIFs from Muybridges collection from the link above locomotion studies and extract the 12 individual photographs from the GIF file. You can extract animated GIF images with Adobe Photoshop, Adobe Fireworks, and several other programs. (Search on extract images from animated GIF in a search engine to find plenty of ways to get the individual images. If you have a Mac, you can use the Preview application, and just drag the individual images from Preview to a separate folder.) Once you have extracted the individual GIF files, set up your animation using the Refresh state with the meta element in the <head> section of your program. To get started, use the following HTML5 script (an1.html in this chapters folder at www.wiley.com/go/ smashinghtml5).
<!DOCTYPE HTML> <html> <head> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <meta http-equiv=Refresh content=0.1; URL=an2.html> <title>Image 1</title> </head> <body> <img src=an1.png alt=one> </body> </html>
107
The individual GIF files were saved as .png files and renamed an1.png through an12.png (the an is for animation). Likewise, the 12 HTML files were named using the an preface from an1.html through an12.html. Once youre finished, youll have a walking horse. If you link the 12th page back to the first, the horse just keeps on truckin.
SMASHING HTML5
WHEN HTML WAS in its infancy, the table element was used for the bulk of page formatting. The advent of CSS introduced a whole new set of rules for formatting and the table was abandoned as a formatting tool and for good reason. However, certain table features in CSS3 have been reintroduced for specific types of formatting. So, although tables still are not general formatting tools, they have key functions for
CHAPTER
110
The story class simply defines the display property as a table. The col1 class, which you can place inside the table, is displayed as a table-cell, and its helpful to think of it as such. The following code (DisplayTable.html in this chapters folder at www.wiley.com/go/ smashinghtml5) shows how to set up a design that can be used to display text and graphics in two columns.
<!DOCTYPE HTML> <html> <head>
111
112
Figure 6-1: Using the CSS3 display property with table values.
As you can see in Figure 6-1, using table-cells is an easy way to set up multiple columns. When you develop more sophisticated Web sites, youll want to use more advanced CSS3 display definitions beyond tables and table-cells, but the table property in CSS3 is available when you need it.
TABLE BASICS
The basic elements of a table are
The table itself, <table> The table rows, <tr> The table cells, <td> The table headers, <th>
Generally, a table caption <caption> is used at the top of the table. A clear table generally has clearly marked column and row headings. The cell in the upper-left corner is often left blank so that the first column doesnt label the row heads; however, the standards state that no cell be left empty. So, the corner cell in BasicTable.html contains r/c to fill the space for now, at least. The following example shows the basic table elements in a simple table. The row and columns both have headings, and the data cells represent data placed in the labeled rows and columns.
<!DOCTYPE HTML> <html> <head> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>Basic Table</title> </head> <body> <table> <caption> Rows and Columns in a Table </caption> <tr> <td>r/c <th>Column 1 <th>Column 2 <th>Column 3 <tr> <th>Row 1 <td>data a <td>data b <td>data c <tr>
113
One of the more interesting aspects of the table tags is that the closing tags are optional. No best practice suggests that closing tags be used or not. Formatting the code so that the rows are clearly delineated is important for making sense out of what you see. By not including the table cell closing tags, the code seems to be a lot clearer and less cluttered, and thats a good thing. So, the closing cell tags are going to be left out unless putting one in will help clarify whats going on in the listing. Figure 6-2 shows what youll see when you launch the file in a browser.
114
Notice that while the <th> tags cause the text to be shown in boldface that the table <caption> does not. That can be fixed with CSS3, and so can the rest of the table to make it more useful. However, to get started with tables, all you need to understand are the basics.
STYLING A TABLE
You dont use tables for general styling work, but that doesnt mean that you can ignore the style of the table itself. The good news in HTML5 is that borders on tables are not a default state as they had been in previous versions of HTML. In fact, the table border attribute is no longer supported in HTML5. If you want lines around the cells, you have to take that responsibility yourself and add them using CSS3. Borders around cells or anything else must be done judiciously or (in the opinion of many designers) not at all.
115
Figure 6-3 shows the results, but before looking at it, examine the CSS3 code carefully. Also, the value § is a character code for a symbol entered using code instead of the keyboard. All UTF-8 characters can be entered this way. Certain symbols such as the greater-than (>) and less-than (<) characters must be entered using this method; otherwise, the parser reads them as part of a tag. Now, take a look at Figure 6-3 to see the page with the borders.
116
Figure 6-3: Borders can interfere with data clarity.
When trying to read the different data elements, the borders get in the way. To fix that, all you have to do is add padding to the borders and height to the cells. In the style, change the td and th element definitions to the following:
td, th { height:50px; border-style:solid; border-width:thin; border-color:#000; padding:20px; }
All that you changed is the height of the cell and the space between the border and the text (padding). However, the difference is significant, as you can see in Figure 6-4. With the added space around the data, the cell value is far clearer. The cells arent too pretty, but thats easy to take care of just remove them.
117
118
By default, the td element left-justifies text, which is desirable in most cases. However, with floating point numbers (numbers with decimal points), numbers are clearer using right-justification. So, one of the style sheet classes included a money class to right-justify financial data. The entire table is given a light yellow background. However, the background color of the table doesnt affect the materials in the <caption> container; so the caption element gets
119
By using a color with less than 100 percent opacity (some transparency), the alternating green is slightly mixed with the light yellow background color. The caption background color is the same as the alternating row green, but it has 100 percent opacity (solid) and you can see it has a slightly different tint. The th elements inherited the tables background color but serve well as column labels without any other adjustments. The cell widths are set to a non-relative value (70px) because the width reflects the fact that the table is optimized for mobile viewing. As a result, the names can take up double rows and not detract from either the design or the tables functionality.
COMPLEX TABLES
The term complex implies tables that are difficult to understand. Actually, complex tables are solutions to tricky problems. If youre using tables to organize data coming out of a database, chances are good that you can use a pretty standard table with a measured set of rows and columns all the same size. When you begin to use a table to display data for just about anything, including data coming from a database, you may encounter situations in which something happens to change the neat set of rows and columns, and you have to make adjustments to fit more into a single row or column than originally planned. In order to understand complex tables, you need to understand the idea of a cell. A table is nothing more than a collection of cells ordered into rows and columns. The intersection of a column and row is the cell. In HTML5, you create cells using the <td> and <th> tags. Figure 6-2, earlier in this chapter, shows basic cells organized into rows and columns.
120
Figure 6-6: A table with equal-size cells and a table with rowspan and colspan.
Figure 6-6 shows that the first cell in Row 2 in the bottom table took up the space of three cells in Row 2 in the top table. In Col 5 of the bottom table, both Row 1 and Row 2 were
121
This example uses a very light gray border so that you can better see the spans vertically and horizontally. However, you dont need the borders to use spans. In fact, without borders,
You can see that the table in Figure 6-7 has 10 cells where a full 4-by-3 table would have 12. Likewise, in the listing, you can see ten <td> tags. Both colspan and rowspan can be a little tricky, but if you think of them in terms of cell mergers, theyre a little easier to understand and work with.
Team coordinator (1) Design team (4) Rich interactive application (RIA) design (2) Front-end development (3) Back-end development (2)
123
124
Basically, the <td> tags that include a rowspan attribute are those that have to be large enough to match the number of team members that will be in the same row. Figure 6-8 shows how the page appears in a browser. The most important thing to remember about tables is that they should be used judiciously. They arent general design tools, but you can use CSS3 to design the look of tabular data set in table elements. So think, Tabular data, tables; non-tabular content, CSS3 only.
126
SMASHING HTML5
THE MAJOR CAPABILITY of Web pages besides displaying text, graphics, and media is loading other pages. Using Web pages, people including designers and developers tend to think of going somewhere or getting something. We even think of helping users with site maps and navigation tools that imply that theyre on some kind of trip. The navigational issues are important and are discussed in Chapter 8.
However, this chapter looks at how links load other Web pages, as well as how theyre used to access alternate style sheets. Included in this examination are the different attributes that are related to loading pages, the details of accessing a page, and CSS3 properties used to both style links and to launch interactive features in those properties.
CHAPTER
128
The ref value alternate stylesheet is an entity that is different from the alternate value that I cover in the next section. You can load as many style sheets as you want; however, the user can only change to an alternate style sheet not to a regular style sheet. To see how the alternate style sheets work, this next example begins with two different external style sheets saved in files named warm.css and cool.css. Then, the Web page code creates the code that loads the warm style sheet as the default, and users may choose to switch between the two styles.
129
The warm and cool color schemes use identical CSS3 code, save for the color values. In that way when we compare them, everything except the color palette will be the same. The following Web page (AlternateStylesheets.html in this chapters folder at www. wiley.com/go/smashinghtml5) uses both CSS external files with one being the default (stylesheet) and the other the alternate (alternate stylesheet):
<!DOCTYPE HTML> <html> <head> <link rel=stylesheet type=text/css href=warm.css title=Warm View (Default)> <link rel=alternate stylesheet type=text/css href=cool.css title=Cool scene> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>Alternative External Style Sheets</title> </head> <body>
The rest of the usage is up to the browser. In testing the different HTML5 browsers, at the time of testing only the Opera and Firefox browsers actually had menu items for selecting different style sheets. If you plan to use alternate style sheets with a general set of browsers, be sure to test them with this program first. Figure 7-1 shows the default setting in the Opera browser with the style sheet selection open.
130
131
In Firefox, the menu to select style sheets is slightly different, but like the Opera browser, it provides users with the opportunity to change styles dynamically if they want.
LINK ICONS
Next to using the rel attribute for assigning style sheets, the most used value is for setting up a small icon to represent the page. Graphic icons can be assigned to the rel attribute using the following format:
<link rel=icon href=graphic.png sizes=32x32/>
In earlier versions of HTML, the relation value was shortcut icon but just icon works as well.
132
In testing the icons with four different browsers (Safari, Chrome, Opera, Firefox), the icons only showed up on the Opera and Firefox browsers. Internet Explorer (IE) was not tested because at the time of this writing, Microsoft was still developing IE9. Also, none of the mobile browsers displayed the page icon. Figure 7-3 shows where the icons (a small green anchor) appear on the Opera and Firefox browsers.
Icons in Firefox
Icons in Opera
In creating an icon, I used a .png file set to the default 32 x 32 pixels. You can use different sizes, but the limits are not clear; however, they are set to where the height and width are the same.
So when the user goes to the page with the video, it has already started loading or it may be completely loaded and ready to go. Here are some other examples:
<link rel=prefetch href=monkeys.html> <link rel=prefetch href=monsterTrucksFull.png> <link rel=prefetch href=http://www.sandlight.com> <link rel=prefetch alternate stylesheet =http://wherever.org/fall.css> href <link rel=prefetch href=sumVa.mp4 title=Summer vacation>
Before you start planning to use the prefetch value with every page that links to a heavy page, remember that its value is dependent on whether users are likely to go to that page. For example, suppose youre creating a Web site for a big department store, and users select from several different graphic displays of products. If the Web page prefetches all the graphics in the selection matrix, its going to add a heavy load to the users computer. So, instead of getting a crisp response, loading the selected page could be sluggish because it has all the other graphics in memory that have been prefetched. One way to optimize prefetch is to organize your pages so that links to a heavy page have a path that limits pre-loading. Pages that include media that require a good deal of load time should have a path to them that has only a few choices with heavy loads.
133
href: Points to external style sheets and icons. media: Specifies the kind of media for the link screen, PDF, print; if no value is assigned to media, the default is all. hreflang: Provides the language of a resource and is purely advisory. type: Identifies the type of file content, such as text/css the MIME types. sizes: Specifies the dimensions of an icon, such as 32x32, 48x48, and other sizes used for graphic figures used as icons. title: Has a real value when using alternative style sheets, but otherwise its advisory.
As youve seen in the examples using the rel attribute, these other attributes are often used in conjunction with rel.
PAGE LINKS
The a element in HTML5, as well as in previous versions of HTML, is one of the key elements in the language. Its primary use is to serve as a means to load a page using the href attribute. Without the href attribute, the <a> tag can serve as a placeholder, but for all intents and purposes, the a element is really a combination of the element and the attribute. Thats why we tend to think in terms of a href or an <a href> tag rather than just the a element by itself. This section examines the nuances of the a element with the focus on the href attribute, but the first topic is using the rel attribute with the a element.
alternate archives author bookmark external first help index last license next nofollow noreferrer prev search sidebar tag up
134
Of these, several are for organizing navigation, and these will be discussed more in Chapter 8. For example, index, first, last, prev, and next (among others) all refer to navigation order. Im introducing them here so that when navigation in a larger context is discussed in Chapter 8, youll be familiar with the concepts. Other values assigned to the rel attribute in the a element context have more to do with identifying certain characteristics, such as the links author or a help link, and I discuss them first.
Author relations
Sometimes, a Web page includes the pages author, and you may want to contact her. To help identify the relation, an author value can be assigned to the link. A common link for such situations is the mailto: keyword used in an href assignment. For example, the following listing (AuthorLink.html in this chapters folder at www.wiley.com/go/smashing html5) uses the author value along with the mailto: link.
<!DOCTYPE HTML> <html> <head> <style type=text/css> /* FFF8E3,CCCC9F,33332D,9FB4CC,DB4105 body { font-family:Verdana, Geneva, sans-serif; font-size:11px; background-color:#CCCC9F; color:#33332D; } h1 { background-color:#33332D; color:#9FB4CC; font-family:Arial Black, Gadget, sans-serif; text-align:center; } h2 { background-color:#DB4105; color:#FFF8E3; } a { text-decoration:none; font-size:9px; color:#DB4105; } </style> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>Author</title> </head> <body> <header> <h1>All about HTML5</h1> </header> <article> <header> <h2> Herein lies the Wisdom of the Ages </h2> </header> <section> Whoaaa!―<em>Wisdom of the Ages?</em>―Thats a lot of responsibility! Why not―<em>The best I can do since 2010?</em> <p> Who wrote this thing anyway?</p> <h3>He did!↓</h3> */
135
In creating the author e-mail link, the a element is styled to get rid of the underline the default style for links and replaces it with a small but noticeable color. To some extent, the entire page draws focus to the link, as you can see in Figure 7-4.
136
When cursor is placed over link to authors e-mail... ... a message appears in the lower-right corner.
The cite element can be confused with the author value assigned to the rel attribute in an a element. First, cite is an independent element, and second, it italicizes the content in a cite container. For example, the following snippet shows how both keywords are used in the same paragraph:
<p>Most of the quotes can be found in the works of <a href=http://www.willieS.com rel=author>William Shakespeare</a>, especially the famous reference book, <cite>Camfords Complete Works of the Bard</cite>.</p>
The text in that code generates: Most of the quotes can be found in the works of William Shakespeare, especially the famous reference book, Camfords Complete Works of the Bard.
The clearest path in the example is made by referencing both the index and the number of up levels. The sequential link types include first, last, next, and prev with each keyword relative to a page within a sequence. For example, the following code goes to the next page relative to a page in the sequence:
<a href=page4.html rel=next>Page 4</a>
The implementation of these link types is different for different browsers, and theyre better used with the link element to map out a sites organization relative to a given page than to direct a page using the a element.
137
To set up the target using an anchor, just assign a tag the name of the anchor like the following:
<div name=developer>
In testing the anchor technique on HTML5 browsers, it failed to work on several. The HTML5 browsers seemed to have adopted using CSS3 to create IDs and use them exclusively. The following example (AnchorID.html in this chapters folder at www.wiley.com/go/ smashinghtml5) shows how to use IDs as anchors:
<!DOCTYPE HTML> <html> <style type=text/css> /*D4CBA0,BD4A14,804130,4F3C33,6D7F59*/
138
139
When using CSS3 IDs for anchors on mobile devices, youll find that your design is not quite as constrained for the small screen sizes. As you can see in Figure 7-5, anchors make it easy to navigate a page on a mobile device. In Figure 7-5, the screen on the left is the initial page on an Opera Mini browser. When the Dogs link is tapped (or clicked on a non-mobile device), the page jumps down to the dog information. Notice that the menu is both at the top and bottom of the page. Generally speaking, if your page is long enough to require IDs for moving around the page, you should have a top and bottom menu. If the page is very long, you can give the nav element an ID and then have each section link to the menu. If you want to set up a link directly to an ID or anchor, you simply add #name to the URL. For example, if somewhere else on your site (or even another site), you want a direct link to the material about cats. Youd simply create the following link:
<a href=http://my.domain.com/AnchorsID.html#cats>
140
In Chapter 8, youll see how to use IDs and anchors in planning a navigation design strategy.
TARGETS
Up to this point, all the links have been ones that replace the calling page with a new page to be loaded in your browser window. However, you can use the target attribute with the <a> tag to assign different ways for a page to appear known as the browsing context. You may select from the following browsing contexts using target:
_self replaces the current page; default if no context is assigned. _blank opens the new page in a new browser window a new browsing context. _parent opens the new page in the parent document of the current page. The parent document is typically the browser windows that caused the current page to open. _top opens the new page in the full body of the current browser window.
The underscore in naming all the browsing contexts is required. So, something like target =blank would not work it has to be target=_blank. In older versions of HTML, the frame and frameset elements were widely used and both could be named as target values. Likewise, the _parent and _top browsing contexts would be used to open a page in a different frame. In HTML5, the major use of the target attribute is to select the _blank browsing context over _self (default).
141
142
143
USING IFRAMES
The iframe element declares an inline frame. Using inline frames, you can load other Web pages or other media within a single Web page. The element represents what is called a nested browsing context. The Targets section in this chapter discusses different browsing contexts in terms of different windows and tabs. A nested browsing context occurs when one page is nested inside another page. Essentially, an <iframe> tag places one Web page inside another.
That tag simply places the source Web page in the upper-left corner of the calling page. To better see the options and control over the iframe, the following program (iframeWeb. html in this chapters folder at www.wiley.com/go/smashinghtml5) embeds two different Web pages inside itself and add several attributes that you can see. 144
<!DOCTYPE HTML> <html> <head> <style type=text/css> /*657BA6,F2EDA2,F2EFBD,F2DCC2,D99379*/ body { background-color:#F2EDA2; } h1 { font-family:Verdana, Geneva, sans-serif; color:#657BA6; } </style> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>Iframe Web</title> </head> <body> <!DOCTYPE HTML> <html> <body> <article> <header> <h1>Before iframes</h1> </header> <section> <iframe name=info width=480, height=320 sandbox=allow-same-origin seamless src=http://www.smashingmagazine.com></iframe>
In the two <iframe> tags, you can see several attributes, some of which youve seen in other elements. The iframe element itself has seven attributes plus HTML5 global attributes. The element attributes are
145
Of these seven, srcdoc, sandbox, and seamless are new. At the time of this writing the srcdoc has not been implemented in any of the tested browsers, but when it is, it navigates to a text/HTML file with information specific for the iframe. The sandbox attribute, available in the Google Chrome browser, is used for restricting the types of content and functionality that can be provided in an iframe, for security reasons. The seamless attribute has not been implemented either, but when it is, all links will be opened in the parent browsing context instead of the nested browsing context inside the iframe. Older browsers and HTML5 browsers that have not yet implemented them ignore all these new iframe attributes. Therefore, you can add the attributes to <iframe> tags to set up good habits so that when theyre available, they can help add security to your Web pages. Figure 7-8 shows how the embedded pages appear on a computer screen. The h1 headings before and after the embedded pages show that the embedded pages are not subject to the CSS3 style of the parent page. Also, you can see that each page is inside another page before and after the insertion of the two other Web pages. If you look at the code, youll see that their dimensions (320 x 480) suggest the viewing resolution for a mobile device. However, when tested on a mobile device, the iframe opened up to display the entire embedded pages. No scroll bars appear in the mobile browsers, so the only alternative to show the entire contents of the embedded pages is to allow them to be thumb-scrolled horizontally and vertically within the iframe. Initially, this may seem to be a
146
SMASHING HTML5
NAVIGATION STRATEGIES
Because this book focuses on HTML5, this chapter shows how to set up different navigation systems using specific HTML5 elements. However, before starting on the more specific tags that are to be used, you need to understand some general Web navigation concepts.
GETTING AROUND A Web site is generally known as navigation, and HTML5 recognizes that fact by introducing a <nav> tag. With simple sites, navigation is simple. However, bad or inadequate navigation can invade virtually any Web site. By the same token, good navigation can make even the most complex site easy for the user to find what he wants.
CHAPTER
Interface design: Jennifer Tidwell best describes interface design for the Web in her book Designing Interfaces. Many of the processes and patterns that Tidwell discusses are covered in this chapter as well, but with nowhere near the depth and scope as Tidwell does, so if you want more information on this subject, be sure to check out her book. Information design: In a far broader topic, information design, Edward Tufte has shown how different kinds of information can be presented so that its best understood. Of special interest to Web navigation design is the notion that information is the interface. In other words, navigation is information arranged so that users can find what they want.
Neither Tidwells nor Tuftes concepts can be summarized in a tidy definition. The idea of interaction is one of responding to another action, such as two people having a discussion. Thats social interaction and its something we do all the time including interaction mediated by the computer, such as text chats. The same concept applies to treating a Web page as a stand-in for another person. The user does something, and the Web page responds from a finite set of choices created by the designer. The better the job that the designer does, the more natural it feels to the user. Trying to create an environment of comfortable interaction is the goal of good interaction design. 148
The better the designer, the more likely the interface will be bad. Excellent developers almost always make bad interfaces.
So, if you aspire to be either a great designer or a developer, youre likely to make a bad interface unless you pay attention. Heres why: Great designers focus on how the page looks, not on the users ability to navigate a site. Designers want to display their creativity, and thats a good thing. However, when that creativity is such that users cant navigate from one page to another, theres a problem. One of the worst user interfaces ever devised was on New Yorks Museum of Modern Art (MoMA) site. The navigation was based around a stack of cubes with no labels. Users were supposed to place their mouse over each cube and a label would appear with the name of the
GLOBAL NAVIGATION
Global navigation in Web pages refers to broad navigation categories that can be placed on every page in a Web site. Global navigation helps users keep track of where they are in a site, so no matter where they go, theyll see a familiar road map. In mapping out a trip from Santa Barbara, California, to Ocean City, New Jersey, youll find major interstate highways. The links go from I-210 > I-15 > I-40 > I-44 > I-70 and finally to I-76. These might be considered the global elements in the 3,000-mile trip from coast to coast. However, between the major interstate highways, youll find smaller connector roads such as CA-134E that connects US-101 with I-210.
Thats certainly global and links would fit nicely on every page like the following: Animal | Vegetable | Mineral However, within each of those general categories, youre going to need something more specific. For example, suppose a user wants to find a breed of dog a Greater Swiss Mountain Dog. The following path would be a possible one depending on the designer: Animal Mammal Dog Breeds Greater Swiss Mountain Dog Each submenu will have lots of choices, so lets consider what elements are available in HTML5 to handle these navigation paths from global navigation.
150
151
Just from looking at the code, you may suspect that this kind of navigation system will quickly overwhelm the page. Figure 8-1 shows what appears even though the possible choices have been drastically cut.
152
Figure 8-1: List navigation.
With a large enough screen and abbreviated choices such as those used in the example, it may be possible to have a navigation system using the <ul> tags. However, with the list system of navigation on mobile devices, the best advice is, Dont even think about it! Figure 8-2 shows how the navigation takes up the entire window in a mobile device. Clearly, as you can see in Figure 8-2, some other system of navigation is required so that the topic can be viewed. The navigation system takes up the entire page. In fact, it looks more like a site map, which I discuss later in this chapter, but it cant be used in global navigation.
153
Figure 8-2: List navigation crowds the display area on a mobile device.
154
<option value=squash>Squash</option> <option value=peas>Peas</option> <option value=rice>Rice</option> <option value=potatoes>Potatoes</option> </select> <label for=minerals>Minerals </label> <select id=minerals name=global3> <option value=tin>Tin</option> <option value=gold>Gold</option> <option value=copper>Copper</option> <option value=iron>Iron</option> <option value=mercury>Mercury</option> </select> </nav> <body> </body> </html>
With that many HTML5 tags, you might expect a much larger Web page. However, as Figure 8-3 shows, very little space is taken up. The HTML5 code has no CSS3 to format the text, and as you can see, the default body font is a serif font and the default menu font is sans-serif. When you use CSS3 for styling, work with the <select> tag for style instead of the <option> tag. If you style the option element,
If the categories appear a bit shallow, you can add greater detail in an outline format using the <optgroup> tag. With each tag, a new subgroup is added. You can nest them in several levels if you wish. The following listing (Optgroup.html in this chapters folder at www. wiley.com/go/smashinghtml5) shows how the optgroup element is used in conjunction with the <select> and <option> tags.
<!DOCTYPE HTML> <html> <head> <style type=text/css> select { background-color:#F2EFBD; color:#657BA6; font-family: Verdana, Geneva, sans-serif; } </style> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>Stratified Drop-Down Menu</title> </head> <nav> <label for=animals>Animals</label> <select id=animals name=global1> <optgroup label=Dogs> <option value=hounds>Hounds</option> <option value=work>Work</option> <option value=terrier>Terriers</option> </optgroup> <optgroup label=Horses> <option value=race>Race</option> <option value=work>Work</option> <option value=show>Show</option> </optgroup> <optgroup label=Rabbits> <option value=pets>Pets</option>
155
For some reason, different browsers have different displays of the category headings generated by the optgroup element. Figure 8-4 shows how the same menu looks on different browsers.
Safari Firefox Chrome Opera Internet Explorer 9
156
Figure 8-4: Using the <optgroup> tag.
Of the four browsers tested, Firefox stands out as unique. The optgroup headings are italicized and the color combinations are preserved when the menu opens. The other browsers display the correct color scheme only when the menu is closed. (Will this give designers another challenge? Yes!)
What that reflects is the HTML5 Document Object Model (DOM). The document is the Web page, menuNow is the name of the form element, global1 is the name of the select element, and selectedIndex is the selected option. Because the selectedIndex is a number between 0 and the number of options in the <select> tag container, it can be used to choose the array element (option), which is selected. Whatever value is stored in the option is passed to the variable named urlNow. For example, the following line has a relative URL of animals/dogs.html:
<option value=animals/dogs.html>Dogs</option>
157
The final line in the JavaScript, window.location.href = urlNow, has the same function as the following HTML5 line:
<a href=animals/dogs.html>
In this context, a different JavaScript function would have to be written for each <select> tag because the function uses a specific reference to that tag (global1). More sophisticated JavaScript could be developed to use variables for the different element names, but the function employed here is relatively short and easier to implement. To test this out yourself, create simple Web pages with the following names:
The Web pages can just have names on them nothing fancy. Then, in the same directory, enter the following HTML5 code (SelectNavJS.html in this chapters folder at www. wiley.com/go/smashinghtml5).
158
Test the page using with Google Chrome or Opera at the time of this writing, those were the only two browsers that had implemented this aspect of HTML5. For the time being, you wont be doing anything with the second two drop-down menus, but at the end of the chapter youll be given an opportunity to complete them with a few additions to the JavaScript file.
CREATING CONSISTENCY
One of the most important features of a good navigation system is consistency. The user has to be able to know where to find the navigation system no matter where she is in the site. If one page has the navigation at the top and the next page does not, in the same site, users may not know where they are relative to where they started or where theyre going. One of the most misquoted pieces of wisdom about consistency can be found in Ralph Waldo Emersons essay, Self-Reliance. By quoting only a part of Emersons thought, many people are misled to believe that consistency is wicked. That famous misquote is . . . consistency is the hobgoblin of little minds. . . . What Emerson fully wrote is, A foolish consistency is the hobgoblin of little minds, adored by little statesmen and philosophers and divines. With consistency a great soul has simply nothing to do. The reason that the quote is important is that Emerson never said that consistency is a bad thing. Foolish consistency is the problem not consistency. When it comes to navigation consistency is essential, and by all means avoid foolish consistency. In other words, dont put a bad navigation system together and then repeat it because its consistent. As far as a great soul having nothing to do, that may be a good thing. With consistency, you dont have to reinvent the navigation system with every new page. A great soul would have different consistencies for different audiences and types of sites; but within the site, the consistency is constant. In her work on grouping elements, Jennifer Tidwell talks about using color-coded sections to assist users in keeping track of where they are. Using colors, you can add clarity to global navigation. The three global categories that have been selected for navigation animal, vegetable, and mineral can be a good example of multiple-consistency (each menu is consistent with the other menus). For the animal category, you might use brown tones; for the vegetable category, green tones; and for the mineral category, nickel tones. Figure 8-5 shows an example where the global navigation is in place and the different pages have a color scheme that differentiates them from one another and at the same time places each in the appropriate grouping.
159
Topic links
Content area
160
When using horizontal and vertical link planes, the user can see all the global links and the links for the current topic simultaneously. More of the viewing area is taken up by the navigation system, but with the larger monitors becoming standard on computers, this isnt that much of a problem. With electronic tablets like the iPad that have smaller screens, it cuts into the usable viewing area, but not a great deal. However, on mobile phones, especially when viewed vertically, the content space is severely reduced. To create an area for a vertical link area with HTML5, you just need to set up a two-column page below the area generally reserved for the logo and global navigation bar.
When that code is added to a style sheet, whenever the mouse hovers over the link (<a> tag), it will change the color to the hover definition. Of course the colors defined for the <a> tag have to be different from the hover, but you can add subtle or blatant signals to the user that the text is a link. Likewise, you can change other features using the pseudo-classes. The following examples will give you an idea:
<!DOCTYPE HTML> <html> <head> <style type=text/css> a { font-family:Verdana, Geneva, sans-serif; font-size:11px; } a:link { color:#cc0000; text-decoration:none; } a:hover { font-size:14px; } a:visited { color:#00cc00; text-decoration:none; } a:active { background-color:#ffff00; } </style> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>Pseudo Classes in Links</title> </head> <body> <a href=#>Click here</a> </body> </html>
161
When using pseudo-classes for navigation, you want to keep the user in mind. Adding strange effects with pseudo-classes can be fun, but you need to ask whether the effects will assist or confuse users. If you can add an effect that users associate with making choices, then that
162
}
color:#2D2B21; background-color:#C9B086; font-size:12px; .content { display:table-cell; width:600px; padding:15px; } aside { display:table-cell; width:100px; background-color:#FFB88C; padding-right:5px; } h1 { font-family:Papyrus; color:#2D2B21; text-align:center; } h2 { color:#A69055; } a { font-family:Verdana, Geneva, sans-serif; font-size:10px; text-decoration:none;
163
When you run this program, you can see that although it provides a wide variety of user choices, its clear. The global navigation along the top provides all the main choices. Then on each page within a global collection, users are able to select choices specific to the selected topic. Figure 8-7 shows what you can expect to see when you test the program in an HTML5 browser on a computer screen.
164
165
Users see an arrow icon and click it instead of a text message. Often, designers will use both text and an image to send users to another page, as shown in the next snippet:
<a href=page2.html><img src=arrowRight.jpg>Next Page</a>
Also, some designers create icons with text embedded in the symbol, as shown in Figure 8-9.
166
One advantage designers find in using graphic text is that they can use any font they want without fear that the user wont have that particular font in his system. It also helps to keep users from getting lost because graphic symbols with text are easy for the user to spot and understand.
LINKING TO A GRAPHIC
Generally, when we think of adding graphics to a page, we think of the <img> tag. After all, that tag is what we use to place graphics on a Web page. However, you also can use the <a href> tag to load a graphic. Instead of assigning a Web page path to the href assignment, assign a graphic. For example, the following line of code loads a blank page with a graphic:
<a href=myGraphic.jpg>My Graphic</a>
167
168
When you test the example, youll see the mans portrait and then the four thumbnails of the man, woman, boy, and girl beneath the image inside the iframe. Figure 8-10 shows the page on a computer monitor screen. As you can see in Figure 8-10, users are instructed to click on the thumbnail buttons to view the different portraits. The interface is fairly intuitive and users know what to expect when they click on one of the graphic buttons. The best part is that only the graphic for the selected portrait is loaded into the iframe instead of loading a new page with all the graphic buttons and other page materials.
169
170
Several different kinds of businesses and social networking sites use similar applications. For example, professional photographers use thumbnails of their photographs that users click to view the full-size images. Likewise, social networking sites can use similar pages to display and load pictures of each users friends without having to leave the page. Because mobile devices have such small display areas, using iframes in navigation designs is quite helpful. Trying to click small text links can be difficult, but as you can see in both mobile browsers in Figure 8-11, the graphic buttons are easy to see and tap for loading the full-size image or other materials into the iframe space.
JavaScript challenge: The first challenge is to complete the JavaScript linkage in the section Using JavaScript to Call a Linked Page. The HTML5 page named Select NavJS.html has three different <select> tags one each for animals, vegetables, and minerals. Only the animal <select> tag contains a JavaScript event function. By adding two more functions to the JavaScript file (globMenu.js) that are similar to the first function but with a different name, you should be able to create functions for the <select> tags for the vegetable and mineral menus. (Its basically a matter of copying
Both of these challenges use the materials in this chapter, and they can be applied to many different applications.
171
III
MEDIA IN HTML5
PART
III
SMASHING HTML5
IMAGES
ONE OF THE most exciting features of HTML5 is the ability to use Scalable Vector Graphics (.svg) files. Artists who use programs like Adobe Illustrator that create vector graphics can save their files as .svg files and put them right into their Web pages. Because .svg files contain vector graphics, images can be made larger or smaller without losing their resolution as bitmapped graphics do. However, you still can use your favorite bitmapped graphics in .jpg, .gif, or .png format for static display. This chapter seeks to clarify using graphics on the Web in terms of the main types of images that are
likely to be used, how to place them where you want on your Web page, and how to optimize them for Web use. Much of this chapter, out of necessity, must use graphic applications that you may not have. These applications include Adobe Illustrator, Adobe Photoshop, and Adobe Fireworks. However, you can substitute other applications you may own, such as Microsoft Paint or Corel Draw. Finally, for drawn graphics and photographs, youre going to have to rely on your own skills, both in terms of artistic abilities and ability to use graphic drawing programs. (In a pinch, you can download public-domain image files from the Web in the file type you need.)
CHAPTER
CHAPTER 9:IMAGES
Fortunately, some recently provided tools help create separate regions to be changed and generate the code needed to make the changes (see the section, Application for Dynamic SVG files from Adobe Illustrator CS5 files later in this chapter.)
177
178
After you finish the graphic and save it as a JPEG file, you realize that its mislabeled. Its a morning glory, not a daisy. Because the file is saved in JPG format, the layer with the Daisy label is not preserved. When you edit the file, youll find that the label is fused with the rest of the graphic. With a PNG file, not only are the layers preserved, but if you use a transparent background, it picks up the background of your Web page, and the transparency is preserved. Figure 9-2 shows that the simple swapping of layers fixes the label problem and provides a transparent background.
CHAPTER 9:IMAGES
With multilayered graphics, preserving the final Web image in PNG format will save editing time. In this particular example, in a JPEG file, erasing the wrong label and replacing it with the correct one in a space below the main image is not too difficult. However, with more complex graphics that include several layers, rather than having to redo the entire graphic, designers can just edit the layer.
179
Figure 9-2: PNG le with preserved layer and transparent background (shown in a graphic editor).
The only unfortunate problem in preserving layers in a PNG file is that it increases the size of the file. The JPEG file is only 33 kilobytes (KB) and the PNG is 225 KB. However, in the next section, youll see how to reduce the size of a file so that you may be able to maintain layers and still have a file that loads quickly.
180
The middle figure is the original one with original dimensions. Had a graphic tool been used to enlarge the image, it would appear un-aliased (without jagged edges). You can see the same thing happen with digital photographs, as shown in Figure 9-4. The original image is on the far left. The enlarged image shows jagged edges and the image is beginning to blur. The image on the far right is so small, its difficult to see much detail and determine the extent to which it appears crushed (pixels pushed together to distort). Use the following program (ImageDistortion.html in this chapters folder at www.wiley. com/go/smashinghtml5) to test some of your own graphics.
<!DOCTYPE HTML> <html> <head> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>Web graphic distortion</title> </head> <body> <!-- Original --> <img src=photo.jpg width=100 height=127> <!-- Enlarged 400% --> <img src=photo.jpg width=400 height=508> <!-- Reduced 50% --> <img src=photo.jpg width=50 height=63.5> </body> </html>
CHAPTER 9:IMAGES
181
Figure 9-4: Enlarged JPG digital photo using HTML5 attributes to enlarge and shrink.
To find the width and height of a graphic, use the mouse pointer to select the image file and then In Windows, right-click it and select Properties Details and read the Width and Height values. You can find the dimensions of a graphic file by moving the mouse over the file. In Mac OS X, Ctrl+click the image file and select Get Info. In the More Info section view the Dimensions showing Width x Height.
Most Web tools, such as Dreamweaver, provide code hinting at the image dimensions. Likewise, virtually all graphic-editing programs show the images dimensions when the file is loaded.
PART III:MEDIA IN HTML5 USING GRAPHIC APPLICATIONS TO MODIFY IMAGE FILE SIZE
When discussing an images size, two different meanings are used: The size of the file in terms of its dimensions The number of bytes it takes up Usually, in this discussion the context should make it clear which sense of size is being used, but for the most part, the term size refers to the number of bytes in a file, and dimensions refers to the size of the image on the screen. Adobe Photoshop is a commonly used application for making adjustments to graphic size and quality. Further, Photoshop provides visual information that designers and developers can use to decide how much byte reduction the graphic can take before its appearance suffers. Figures 9-5 and 9-9 show this process. (Figures 9-6 through 9-8 show information about the files and how they appear on a Web page.)
182
CHAPTER 9:IMAGES
183
In looking at Figure 9-6, you can see that both have identical dimensions (432 x 343), but one has 12 KB of information and the other has 139 KB. The reason for beginning adjustments by comparing the best and the worst quality as implied in the file size is that visual differences are more apparent. Perception studies have found that examining minute differences tends to gloss over those differences, whereas extreme differences are clear, so when you begin making adjustments, its better to start with the big differences. Figure 9-7 shows the two files on a Web page.
As you can see, the lowest-quality image (left) and highest-quality image (right) are very similar. In the context of other materials on a Web page, some quality differences may appear. However, images that have the characteristics of those two shown in Figure 9-7 dont suffer much in appearance on the Web when file size is reduced. 184 A bigger difference with JPEG files sizes can be seen with digital photos. In Figure 9-8, the photo on the left is the lowest quality (8K) and the one on the right (115K) is the highest, with corresponding file sizes.
CHAPTER 9:IMAGES
The differences between the two photos with the different settings is minimal, but the difference in the kilobytes is quite large 8K versus 115K. On a video monitor, the image in Figure 9-8 on the left has poorer definition around the edges, but if the primary audience has very low bandwidth available, cutting down the size of JPEG files wont significantly cut down on the quality of the image. The image in Figure 9-8 was photographed with a Webcam, and digital photographs taken with higher-quality cameras show far more detail that may be lost with the loss of information taken out when a file size is reduced. However, very high-quality digital photos have to be reduced significantly in size to be practical for the Web.
186
CHAPTER 9:IMAGES
<body style=background-color:#BAD9CB > <!-- Safari, Chrome and Opera --> <img src=logo500x400.svg width=100 height=80> <img src=logo500x400.svg width=200 height=160> <img src=logo500x400.svg width=300 height=240><br> <img src=logo500x400.svg width=500 height=400> <!-- Firefox and Opera <object width=100 height=80 type=image/svg+xml data=logo500x400.svg></object> <object width=200 height=160 type=image/svg+xml data=logo500x400.svg></object> <object width=300 height=240 type=image/svg+xml data=logo500x400.svg></ object><br> <object width=500 height=400 type=image/svg+xml data=logo500x400.svg></object> --> </body> </html>
At the time of this writing, Firefox did not use the <img> tag with .svg files but required the <object> tag instead. The Opera browser worked with both formats. Figure 9-10 shows the results. As you can see, the logo in Figure 9-10 looks the same no matter what size its displayed in.
187
Figure 9-11 shows a color figure (Figure 9-8) that is turned into a grayscale using CSS only.
188
Using this technique is a quick way to see how the figure looks in a grayscale before rendering it in a grayscale mode. If youre updating a site, and you want to view the images on the page in grayscale, you can add the CSS and test it on Internet Explorer first. If you want to keep the file size down and the quality up, a JPEG image in grayscale instead of color will cut the file size in half.
CHAPTER 9:IMAGES
189
The right and left placement of the image is simple. All thats required is the assignment of left and right values to the align attribute. Figure 9-12 shows the placement of the image in both the left and right positions.
190
In Figure 9-12, the page on the right looks okay, but the page on the left jams the text right up against the image. Also, the page is wholly dependent on the users page settings and size. In other words, using the align attribute for placing images can make your page look awful. Figure 9-13 shows two other views of the same page that transform its look. In Figure 9-13, the figure on the left shows the text scattered all over the page, while the figure on the right, a mobile device, shows the image just fine, but the text is just one word wide, snaking along the side of the picture. The rest is below the view area.
CHAPTER 9:IMAGES
191
192
CHAPTER 9:IMAGES
First, try out the program on your computer. You should see exactly what you saw when you originally tested it (refer to Figure 9-12). Now, try it out in a mobile browser. Instead of a large image pushing all the text to one side, you see a smaller image surrounded by text, just like the one on your computer. Thats because the Web page was able to use the JavaScript to determine whether the page was loaded by an iPhone or some other platform or device. Place the Web page file and both of the images in their folder into the same directory on a server. When you test it, it looks like it was made for the iPhone, but it was really made for the iPhone or any other device. Using this and other JavaScript code, you can do a lot more with HTML5 than you can with just HTML5 by itself.
193
The JavaScript used in the example is as minimalist as possible. However, the logic of it can be outlined as follows: Place the contents of navigator.appVersion into a variable named envir (short for environment).
APPLICATION FOR DYNAMIC SVG FILES FROM ADOBE ILLUSTRATOR CS5 FILES
194 Adobe Illustrator CS5 (AI) has an added feature, Adobe Illustrator CS5 HTML5 Pack, available at http://labs.adobe.com. Its designed to allow graphic designers using AI to easily convert their .ai files to .svg files containing parts that can be dynamically changed using HTML5.To give you an idea how it works, the following example begins with a simple graphic image in AI. It has two layers, and on one of the layers, the designer wants variable color that can be coded in HTML5. The layer to be given a variable feature is selected and viewed in the Appearance panel (as shown in Figure 9-15).
CHAPTER 9:IMAGES
The (X) in Figure 9-15 indicates that the Fill is a variable that can be changed with HTML5. In order to access the feature to be changed (the fill color in this case), AI generates code for the SVG file format that can be viewed and/or saved during the conversion from an .ai file to an .svg file. During the conversion process, the designer clicks the Show SVG code button, and finds the layer name of the variable feature. In this example, the specific SVG code was the following:
<g id=Button> <ellipse fill=param(SVGID_2__FillColor) #A35563 cx=50 cy=50 rx=40 ry=40.5/> </g>
The id with the value Button is from the name of the layer in AI. The param name value is SVGID_2__FillColor, which is automatically generated by AI. In order to work the SVG information into an HTML5 program, the .svg file must be referenced in an <object> element and the parameter in a <param> tag. The JavaScript file Param.js is also automatically generated by AI and must be loaded in the <head> container in order for Firefox to correctly parse the code. The following code (AI2svg.html in this chapters folder at www.wiley.com/go/smashinghtml5) works with Firefox, Safari, Chrome and Opera browsers but with some differences in display.
<!DOCTYPE HTML> <html> <head> <script src=Param.js></script> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>AI -> SVG</title> </head> <body> <article> <section> <figure> <object type=image/svg+xml data=butnBkground.svg> <!--No param tags --> </object> </figure> <figure> <object type=image/svg+xml data=butnBkground.svg> <param name=SVGID_2__FillColor value=#cc0000 /> </object> </figure> </section> </article> </body> </html>
195
In order to illustrate the sequence of processes, Figure 9-16 shows the original AI file and the results of the output in Opera when the page AI2svg.html loads.
Adobe Illustrator le
Figure 9-16: The original AI le is transformed into an SVG format with variable ll color.
196
The Param.js and .svg files must be in the same folder as the HTML5 page, just as external CSS3 and graphic files are expected to be either in the same folder as the HTML5 that calls them or in the path specified by the HTML5 code. The best part, though, is that designers and developers can focus on the HTML5 tags while Adobe Illustrator CS5 takes care of generating the JavaScript and the parameter names. Of course, this means that designers can use vector graphics and have dynamic features in their AI creations.
CHAPTER 9:IMAGES
4. Using HTML5 and CSS3, create a Web page with three rows. On the left side place the highest-quality images, and on the right place the lowest quality. 5. Between all the images, place fill text of your choice. This is a good time to look up lorem ipsum on the Web. Figure 9-17 shows the general format.
Figure 9-17: Displaying the different types and qualities of graphics in text.
197
This exercise has two purposes: To provide you with an exercise in placing text work with CSS3 from this chapter and previous chapters. Using the align attribute in the <img> tag has serious limitations. To drive home the idea that all changes to images must be done using software that changes the characteristics of an image before you put your Web page together. For those who want to do more with vector graphics, try out the Adobe Illustrator CS5 HTML5 Pack. If you do not have Adobe Illustrator CS5, you can download a 30-day trial free. Try creating variables out of different parts of an AI design using multiple layers with names that become the ID name of the parameter youll change.
SMASHING HTML5
10
SOUND
ADDING SOUND TO Web pages allows developers to create a wide range of Web sites. Sites that play music, provide instruction, or add sound effects certainly widen the range of possibilities of what you can do with HTML5. This chapter examines how to prepare sound for the Web and how you can use sound to help your Web pages make some noise.
Youll learn how to work with the different <audio> tag attributes and settings. Also, youll see how different browsers handle sound and different sound files. As with graphics, specialized programs are available to create audio and edit it. So, after examining the basic HTML5 elements and attributes, this chapter goes on to show you how to create sounds for your Web site.
CHAPTER
10
The src attribute works just like it does in an <img> tag its a reference to the source of the file. However, to get the audio to play, you need to look at the attributes.
AUTOPLAY
The autoplay attribute is fairly self-explanatory. As soon as the page loads, the sounds begin to play. Before adding the autoplay attribute, you want to be sure that all your users are going to be okay with listening to whatever youre playing. One way to guarantee that users will not return to a page is to have a continuous sound that automatically turns on. That concern aside, the following script (BasicAudio.html in this chapters folder at www. wiley.com/go/smashinghtml5) shows how to create a simple page that begins playing as soon as its launched:
<!DOCTYPE HTML> <html>
200
<head> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>Basic Audio</title> </head> <body> Audio is between the lines<br> ---------------------------------------<br> <audio src=jazz.wav autoplay></audio> <br> ---------------------------------------</body> </html>
You can test that script with any browser except Google Chrome because its the only one that doesnt recognize sound files in the .wav format. Use an .mp3 or .ogg sound file instead for Chrome testing.
CONTROLS
As noted, if your sound (music, sound effects, or even just talking) annoys your users, theyre not going to return. So, how do you control sound? The easiest way is to add the controls attribute. As with autoplay, you dont have to give it a value. Just include it within the <audio> tag, and it automatically appears. Try the following program (Controls.html in this chapters folder at www.wiley.com/go/smashinghtml5):
CHAPTER 10:SOUND
<!DOCTYPE HTML> <html> <style type=text/css> /* 694703,A83110,E89F06,F5D895,B3CF83 */ body { background-color:#B3CF83; font-family:Verdana, Geneva, sans-serif; color:#694703; } h1 { font-family:Braggadocio, Arial Black; color:#A83110; } </style> <head> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>Controls</title> </head> <body> <article> <header> <h1>Jazz Tonight</h1> </header> <section> <p>Click the triangle to start the show: </p> <audio src=mists.ogg controls></audio> <p>The || two pipes symbol stops all of this. </p> </section> </article> </body> </html>
201
When you run this program, be sure to use a browser compatible with the audio file. (Use a .wav file if the .ogg file type doesnt work with your browser.) Depending on the kind of browser you use, youll see different player controls. Figure 10-1 shows how the different browsers look. (The Google Chrome browser is shown with the sound actually playing.) About the only common feature of the audio control bar is the triangle start button on the far left, and the sound on/off toggle on the far right. The stop/pause button is similar as well, but the graphics of each is unique. (The different control bar images may give designers fits as they try to design a page with audio to be fully compatible with all browsers.) Providing some kind of control for users is essential. The Chrome browser provides a nice big bar so that the user can clearly see where she is relative to the beginning and end of the audio. For instructional audios, the scrubber bar (the vertical bar you can see in the Chrome browser in Figure 10-1) is important so that the student can drag the scrubber bar to review those portions of a lesson that are difficult to understand.
202
Chrome Firefox
PRELOAD
The preload attribute of the <audio> tag can be an important one because it starts preloading the audio before its played. In that way, users dont have to sit and twiddle their thumbs while the audio loads after they press play. The simplest format for the preload attribute is just like the controls and autoplay it just needs to be added without a value, as the following shows:
<audio src=Shadows.wav preload controls></audio>
When preload is employed, you can use autoplay, but Im not sure that it makes much sense to do so. Autoplay starts the audio playing as soon as the page loads, while preload is used to load an audio file before the play command is issued by the controller. You can assign values to the preload attribute:
none: Having none as a value may seem strange, but some browsers may be set to
automatically preload audio files. However, if the chance of using a particular audio is remote, the developer may decide not to use Internet resources and so assigns the none value to the preload attribute.
CHAPTER 10:SOUND
metadata: All audio (and video) files have metadata like duration or some other sound data that the sound author placed in the audios file. When the chance of using an audio file is low, but (just in case) loading the metadata is reasonable and doesnt take up much in the way of Internet resources. auto: If the preload attribute is present, it automatically preloads the audio file
information. The auto assignment simply acts as a reminder that the file is going to preload. (Its the same as not have any value assignment to a preload attribute.) The more varied your audience and the more audio in your Web page, the more you want to provide the preload attribute with options.
LOOP
When you want a sound to endlessly repeat itself, you use a loop. The advantage of using a loop is that you can take a relatively short piece of music and have it repeat itself so that it sounds like a full composition. In this way, you can use a minimum amount of Internet resources and have continuous music. The format is like the other attributes that act like Booleans theyre either off or on. The following is an example:
<audio src=Shadows.wav autoplay loop></audio>
In that line lies the seeds of its own destruction. For many good reasons, users may want to turn off sound. You can use JavaScript to put together a simple routine that will do that, but its easier simply to add the controls attribute and let the user turn it off. However, some designers, with good reason, would rather not have the audio control anywhere in the design; they believe that some nice music would be an integral part of the design. In that case, start looking up the JavaScript to turn the thing off. No matter how nice a piece of sound is, repeated endlessly it becomes brainwashing, and thats not allowed by the Geneva Convention.
203
Table 10.1
Browser
Chrome Firefox
WAV
No Yes No Yes Yes
OGG
Yes Yes No* No No
* Microsoft announced that IE9 would be supporting the OGG format, but in the beta version of IE9, it did not.
204
The chore of making multiple versions of audio files may be annoying, but even if you programmed it in JavaScript, youd need multiple copies of the media. (In Chapter 9, multiple copies of a graphic file were required for mobile and non-mobile platforms that used JavaScript to sort out whether the page was being viewed on an iPhone or something else.)
TYPE ATTRIBUTE
When setting up several different types of audio sources to be sure that all HTML5compatible browsers will play it, you can enhance the process by adding the type attribute to the <source> tag. The information in the type attribute tells the browser whether it should even attempt to load the file. For example, the following snippet shows the format:
<source src=mists.ogg type=audio/ogg>
The reason for including a type attribute is to save time. The interpreter in the browser looks at the line and realizes that the type indicates that it can either play it or not. If not, it doesnt even bother trying. For example, suppose you were given a choice of taking two tests one in HTML5 and the other in quantum physics. Unless you have a background in quantum physics, youre not going to waste your time trying. However, knowing that a test will be in HTML5, you feel like you can give it a shot. Its the same with the type attribute. If it sees the type and determines, I cant play that, it doesnt try.
CHAPTER 10:SOUND
If the type attribute is not in place the browser will try to load it, and if it fails, it then goes on to the next <source> tag and gives it a try. The following snippet shows all the types:
<audio controls> <source src=instruction3.ogg type=audio/ogg> <source src=instruction3.mp3 type=audio/mpeg> <source src=instruction3.wav type=audio/wav> </audio>
All values must be valid MIME types. The valid ones follow the media-type rule defined in W3C specifications for HTML5. The type attribute is optional, but if your site has a lot of traffic, you want to cut out every unnecessary call. The type attribute helps you do that. For more help, you need to consider the codec parameter in the next section.
205
So remember, codecs and file types are horses of different colors. If your Web pages can use full codec information on a file, you may as well use it. Otherwise, some browsers may attempt to launch the sound only to find that the codec is incompatible.
The above snippet does not show all possible codecs of all audio types. However, it represents the typical kinds of codes used in Internet audio.
206
CHAPTER 10:SOUND
207
Figure 10-3: The Sound Recorder application in Windows 7.
Once youre ready to start recording, click on the red circle, and begin talking. As you talk, youll see a green bar appear next to the timer in the middle of the recorder bar. If that bar is not moving as you talk, that means your microphone is not working correctly. Otherwise, youll see the green sound bar bounce in and out as you speak. When youre finished, click on the Stop Recording button a blue square. (In Sound Recorder in Windows XP, the Stop Recording button is a black rectangle right next to the red circle that starts the recording.) When you click the Stop Recording button, a new Save As window opens and you can select the directory where you want to save your audio recording. As noted, in Windows 7, the only option is in .wma format (Windows Media Audio). If youre using the Windows XP version, select Save or Save As to open a dialog box to use to choose the directory, filename, and format which is .wav (but not .wma!). If youre using the older version of Sound Recorder, youre all set with a .wav file that you can play using the HTML5 <audio> tag. Otherwise, youll have to convert the .wma file to an acceptable format for HTML5 browsers.
208
Figure 10-4: Sound Studio timelines and the Input Levels window.
Converting les
If youll be using audio for general audiences, youre going to need either
A sound editor that saves audio les as .wav les and either .mp3 or .ogg. A conversion program. A simple search on the Web will reveal several. For example, if youre
using the Windows 7 Sound Recorder, youll need a program to convert from .wma format to.mp3, .wav, or .ogg. Generally, the process is quite simple for either Mac or Windows platforms. A variety of conversion products are available, but several for Windows 7 can be found at http:// software-download.name/audio-converter-windows-7/. On the Mac, I tested Switch Sound File Converter (http://download.cnet.com/Switch-Audio-Converter/30002140_4-10703967.html) and found it to be easy to use; it converted typical Mac sound le types (like .aiff les) to sound les recognized by the HTML5 browsers. Do a Web search and youll nd far more converters for both Windows and Macs.
CHAPTER 10:SOUND
To make a recording, click the red Record button. If you want to pause to gather your thoughts, click the Pause button. Once youre finished, click the Stop button and select File from the menu bar. If you choose Save or Save As, you can save the file for HTML5 browsers in .wav format. However, if you select Export with QuickTime, the file will be in .mp3 audio format. So, using Sound Studio on the Mac, you can generate two of the three HTML5 formats available to store your audio recordings.
TRANSITION SOUNDS
A subtle yet effective interactive sound can be used to add an audio component to page transitions. In a tactile world of buttons, switches and doorknobs, our actions often evoke sounds. You can make your Web links do the same thing. Use the following steps to create a simple transition: 1. 2. 3. 4. Navigate to www.flashkit.com/soundfx. Select Sound FX from the home page menu. Select Interfaces > Clicks from the Interfaces Categories. Select a click sound that you like. If youd rather, choose a Zoop, Zang or Zing just be sure its short in duration. 5. Download both .wav and .mp3 versions. 6. Rename one file click.wav and the other click.mp3. 7. Place the .mp3 and .wav files in a folder. Now, in the same folder where you placed the sound files, place the following two pages (TransitionSound.html and SoundOpen.html in this chapters folder at www. wiley.com/go/smashinghtml5). 209
210
<html> <head> <style type=text/css> body { font-family:Verdana, Geneva, sans-serif; color:#cc0000; font-size:24px; } </style> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>Sound on Open</title> </head> <body> <audio autoplay> <source src=click.wav > <source src=click.mp3 > </audio> This page clicks. </body> </html>
Save both HTML5 pages in the same folder along with the two sound files. Test the HTML5 pages with several browsers. When you click the link, it opens a Web page and an <audio> tag with the autoplay attribute should play the click sound right after the page loads. If you have a site where the links go back and forth, the sound plays almost simultaneously with the
CHAPTER 10:SOUND
click action so that it sound as though clicking the link made the sound. Of course, thats the idea. Otherwise, if the page takes even a little while to load, the click sounds when the page comes up sort of like clicking itself into place. At the time of this writing, the Opera and Firefox browsers on the Macintosh did not work when the type attribute was added to the <source> tag, but with Safari and Chrome it did. However, when the type attribute was omitted, the Web pages worked fine with all the Macintosh HTML5 browsers. In testing on Windows 7, the latest versions of Firefox and Safari did not generate sound, but both Opera and Chrome did with the same files. (This is why Web developers age quickly.) However, HTML5 is still young, and many of the features of HTML5 are still in development. So, by the time youre reading this, these differences may have been resolved.
211
Youll need to download (or create) three sounds, each in both .wav and .mp3 formats. Use short sound effects and when each of the icon buttons is clicked, the sound plays by the page loading in the iframe. The page being loaded has nothing but the sound, and for this demonstration, it has a background color matching the speaker icon color. Place all the pages and the six sound files in the same folder. (The following files are in this chapters folder at www.wiley.com/go/smashinghtml5: SoundFrame.html, sound1.html, sound2. html, sound3.html.)
212
CHAPTER 10:SOUND
213
You can have a lot of fun testing different sounds. Be sure to test it on different HTML5 browsers. Also, try to make your own sound effects you can recruit your dog, cat, and parrot (who was once owned by a sailor).
214
SMASHING HTML5
11
VIDEO
ONE OF THE most important features added to HTML5 is video. If youve used YouTube, youre aware of the power of video on the Web. Likewise, Adobe Flash users have embedded video in their programs for years. So, video on the Web isnt exactly new. However, the new features of HTML5 make it possible to access video directly from an HTML5 Web page, and thats something that HTML has never been able to do in previous builds without a link to a Flash .swf file or some other binary file that streams video independent of the tags placed in an HTML file. An important caveat to add here is that the video that is displayed by your Web page is not true
streaming video; instead, its a type of progressive download. As the video is downloaded from the Web server, its displayed by the Web page, so it can be slow. In fact, most videos created by Flash hobbyists are very likely to be this kind of video. Streaming video, at this point, requires a streaming video server like Adobe Flash Media Server. However, you can expect to see developments in true streaming as HTML5 video becomes more popular. If youve read Chapter 10, youll find many of the video tags familiar. This chapter looks at many of the same tags, like <source>, but with an eye to loading and playing video.
CHAPTER
11
216
In order to test and run this file, you need a Safari browser because, at the time of this writing, thats the only browser that it works with. (The browser is free, so go ahead and try it.) When you run the program, youll see your video play on the Safari browser. The way the controls are set up, youll have to wait until you see an image, which means the video is ready. Click the start arrow on the controller and you should see your video play. Figure 11-1 shows what you can expect to see if you play and pause the video. Obviously, youre going to want your video to play on more than one browser. If your video can be viewed using only a single browser, youre going to miss a lot of users. Fortunately, HTML5 has a simple way of solving the problem. Within a <video> container, you can add as many <source> tags as you want. The source attribute (src) is moved to the <source> tag. If you place several <source> tags in the <video> container, the browser will look at the video files and select the one it knows how to play and automatically play it. If it can play more than a single type of video format, it starts playing the first one it recognizes and ignores all the rest. All this can be done using HTML5 without having to break out JavaScript. The following snippet shows the basic format of accessing video files in this manner:
<video> <source src=someVid.3gp>
CHAPTER 11:VIDEO
<source src=someVid.mp4> <source src=someVid.ogv> <source src=someVid.webm> </video>
Although many different formats are around for digital video, the ones that will be used for illustration and discussed in this chapter are the following:
217
H.264: .mp4 and .mov OGG: .ogv WebM: .webm 3GP: .3gp
At the time of this writing (and quite possibly for the future) different formats are going to run on different browsers. However, using the <source> tag, you can easily reference several different browsers. For example, the following code (SimpleVideoSource.html in this chapters folder at www.wiley.com/go/smashinghtml5) plays the same video on any of the browsers tested, including two mobile browsers.
<!DOCTYPE HTML> <html> <head> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>Selective Video</title> </head> <body> <video controls preload=auto> <source src=multiformats/mbAux1.3gp> <source src=multiformats/mbAux1small.mp4>
When I tested the program with different browsers and platforms, all of them were able to find the file format they preferred and play both the video and sound. Figure 11-2 shows the video playing in a Safari mobile browser on an iPhone.
218
The quality of the play was fairly consistent on all browsers. On both the Safari mobile browser and Perfect Browser for the iPhone, other than the screen size, the video quality was quite good. Most important, it loaded quickly.
CHAPTER 11:VIDEO
At this point in time, going beyond what can be tested and proven is a bit risky. However, I think that we can look at four different kinds of file containers and codecs and use the four listed at the beginning of the chapter. The 3GP container format is related to MPEG-4, but its actually an H.263 format, and its primary adoption has been for mobile devices like the iPhone. Table 11.1 shows the compatibility matrix of the major browsers on which video tests have been made or decisions have been made.
Table 11.1
Browser
Chrome Firefox
OGG
Yes Yes No Yes No No
WebM
Yes Unknown No Yes No No
3GP
No No Yes No Yes Yes
219
* Microsoft announced that it would support H.264, but IE9 was unable to play MP4 format at the time of testing the beta version of the browser.
Given the array of compatibility between browsers and file formats, you need to know how to convert between the different formats. This next section examines how to do that. The conversion needs to happen first between the file type used by the recording instrument (a camera or screen-sharing application) or video-editing software. The second type of conversion is between the video fully prepared for the Web and the possible types of files required for HTML5 pages. Once all the types of files needed are ready, all you have to do is place them in <source> tags within a <video> container.
220
The Miro Video Converter is available free of charge at www.mirovideoconverter.com. The conversion process involves dragging or loading the file to be converted to a central window and then clicking a Convert button. Its very simple and adaptive. For .ogv files, select Theora from the menu and then click the Convert button. The resulting file has the extension .theora.ogv, but by removing the .theora, you can run it fine with just the .ogv extension. In converting from an .mp4 file to the .ogv file, the file size was reduced from 54MB to 11MB a fivefold reduction.
221
As you can see in Figure 11-4, AME provides a good deal of file information. In the left panel, it visually displays the file youre currently working with.
222
Figure 11-5: Displaying video in Adobe Device Central.
In looking at Figure 11-5, you have an excellent idea of what your video is going to look like in the target device. Adobe Device Central provides several different views so that you can optimize the video prior to placing it on the Web.
The focus is on getting the materials from the camera into a file format that can be used immediately or converted for use with HTML5.
223
SMALL CAMCORDERS
The primary drawback of webcams for making videos that can be embedded in HTML5 is that theyre tied to a computer either built in or tethered to a USB or IEEE 1394 Firewire port. This makes mobile use of webcams problematic, even for highly portable laptops. Wireless webcams are available, but they tend to have a limited range and are more expensive. However, several highly portable alternatives are available. The most common are video cameras built into mobile phones. Mobile phones used during the protests following the 2009 Iranian elections provided worldwide exposure of the government retaliation against those who protested election fraud. Because Western journalists were banned from covering the election aftermath, the news coverage was provided by video from mobile phones broadcast on YouTube and announced through Twitter.
Figure 11-6: Small high-denition camcorders are adapted for the Web.
224
Besides Flip, HD video cameras also are available from Kodak, in the form of the Kodak Pocket Video camcorder. Both the Flip and Kodak camcorders are solid state recorders, so no digital video tapes or removable flash memory cards are required just as none is required for mobile phones. The small camcorders come packaged with limited video-editing software and save video in H.264 format on both Windows and Macintosh computers. The quality of the video is as high as much larger and more expensive camcorders, and theyre far more portable. They were designed from the ground up for use in creating videos for social-networking sites like Facebook and YouTube; as a result, their native output files are custom-ordered for displaying with HTML5 video elements.
STANDARD CAMCORDERS
The term standard here refers to handheld camcorders with such features as zoom lenses, mini DV tape cassette storage, flash memory cards, and other features that can be placed on larger platforms. The gamut of camcorders has widened to the point where the range is from inexpensive ones used for personal family recordings all the way to those used by independent filmmakers. Like the (really) small camcorders the standard ones come with USB or IEEE 1394 Firewire connectors. The connectors can them be fed directly into video-editing software like Adobe Premier, Apple Final Cut, or Vegas. The edited video can then be saved to a format that can be used by HTML5 browsers.
Basically, all that Camtasia requires is for the user to select the screen and the microphone and click the Rec button (as shown in Figure 11-7). Available for Windows 7 and Macintosh OS X, its a widely used software package for trainers and educators who work on a project on the screen so that viewers can follow along. Another screen video capture application can be found as part of the Apple Quick-Time Player. It automatically saves files in .mov (.mp4) format that are ready to be used with an HTML5 Web site. The recording process is extremely easy, and other than selecting the microphone, its a one-step start-and-stop recording operation.
225
These attributes of the <video> tag are discussed in concert with the <source> tag because not all browsers read the same file types, so several different sources must be listed. The <source> tag allows the browsers to choose which video file is compatible with their own video display functions (as was shown at the beginning of the chapter).
The type assignment can be made with or without the codec. If you dont know the codec, you can leave it blank and rely on the type to let the browser know whether it can play the file. If you know the codec or multiple codecs, you can place more than one codec in the codecs assignment list. Where youre not sure youre better off leaving the codecs assignment blank. The following (TypeVideoSource.html in this chapters folder at www.wiley.com/go/ smashinghtml5) shows the type assignments for the four major types of video files you can use on the Web.
<!DOCTYPE HTML> <html> <head>
226
<meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>Selective Video</title> </head> <body> <video controls preload=auto> <source src=mbAux1.3gp type=video/3gpp; codecs=mp4v.20.8> <source src=mbAux1small.mp4 type=video/mp4; codecs=mp4v.20.8> <source src=mbAux1small.ogv type=video/ogg; codecs=theora, vorbis > <source src=mbAux1small.webm type=video/webm; codecs=vorbis,vp8 > </video> </body> </html>
To determine the type and codec of a file, you can find several different programs on the Web. One available at no cost with versions for Windows, Macintosh, and several different Linux operating systems is MediaInfo available at http://mediainfo.sourceforge.net/en.
POSTER
The poster attribute is used with large videos and slow Internet connections. Its simple to use, and if you know that itll take a while for your video to come to the screen and begin playing, the poster gives the user something to look at while waiting. The format is simple as shown in the following snippet:
CHAPTER 11:VIDEO
<video poster=message.png> <source src=multiformats/mbAux1.mp4 type=video/mp4> </video>
Notice that the poster attribute is in the <video> tag even though all the file information is in the <source> tag. There is no conflict between the video attributes and those in source.
PRELOAD
The preload attribute of the <video> tag would seem like a natural to include in all Web pages that use video. As soon as the page loads, the video starts loading. That may be important for a page with a single video as the main feature of the page. However, if its a minor part of the page or if several videos are on a single page, preloading can gobble up resources. So, while useful, the attribute needs to be employed judiciously. It uses the following format:
<video preload=auto> <source src=mbAux1small.webm type=video/webm; codecs=vorbis,vp8 > </video>
The preload attribute has several values it can be assigned. Theyre identical to audio preload values.
none: Having none as a value may seem strange, but some browsers may be set to automatically preload video files. However, if the chance of using a particular video is remote, the developer may decide not to use Internet resources and so assigns the none value to the preload attribute. metadata: All video files have metadata like duration, width, height, or some other data placed in the source file. When the chance of using a video file is low, loading the metadata is reasonable and doesnt take up much Internet resources. auto: If the preload attribute is present, it automatically preloads the audio file information. The auto assignment simply acts as a reminder that the file is going to preload (same as not having any value assignment to a preload attribute).
227
The more varied your audience and the more video in your Web site, the more you want to provide the preload attribute with options.
LOOP
A video loop is something that you must plan carefully lest you run off all your viewers. A loop means that the same video is going to start from the beginning again as soon as it ends. The following is an example:
<video loop controls> <source src=phantom.3gp> </video>
AUTOPLAY
Like the loop attribute, the autoplay attribute needs to be used with some forethought when employed with video. The autoplay is a combination of preload and automatically starting the video playing. The format is a Boolean one and setting the autoplay in the <video> tag is all it takes to start it.
<video poster=wait.jpg autoplay> <source src=phantom.3gp> </video>
228
In the above snippet, the user has no control to stop the video from playing, but without a loop attribute, it will just play once and stop. If the page is meant to be nothing but the video, its fairly safe to use autoplay without a controller. Also, the snippet has a poster to let the view know whats coming, just in case theres a long load. In the context of a Web site when using autoplay, be sure to include a link for the next page just in case the user doesnt want to view the video more than once.
CONTROLS
The controls attribute generates a graphic control panel beneath the video. It allows the user to perform the following functions:
Start the video Stop the video Mute the video Control the sound volume Time position Scrubber control
The controls attribute is a Boolean and is implemented as shown in the following snippet:
<video controls> <source src=multiformats/mbAux1small.webm> </video>
CHAPTER 11:VIDEO
The implementation of the controller is slightly different on the different browsers (as they are on the audio controller). Figure 11-8 shows the Opera and Chrome browsers displaying the same video.
Figure 11-8: The Opera (left) and Chrome browsers displaying video controller.
The differences in the controls are mostly style, but as you can see in comparing the Opera and Chrome browsers, the Opera browser displays the time in the current video relative to the total time, while the Chrome browser shows only the current time position of the video.
229
Most videos maintain a 4:3 ratio such as 320 x 240; however, with HD, the ratio is different, and sometimes editing has changed a videos dimensions. You can select a video file and look at its properties, but sometimes you wont be given the dimensions. For example, on a Macintosh OS X, dimension information for .ogv and .webm files was not provided in a properties query ( + I) The same video in an MPEG4 format, though, showed the dimensions.
230
IV
PART
IV
SMASHING HTML5
12
JAVASCRIPT IS A Web programming language that you can use with HTML5. It can be used to access certain parts of your Web pages written in HTML5 and do other things that simply cannot be done without JavaScript. This chapter introduces some basic features that are going to be used specifically with HTML5 elements. JavaScript is considered a scripting language because its interpreted by the browser at runtime (when you actually open a Web page) rather than compiled and stored on your computer as a binary file. Slightly different versions of JavaScript can creep in with different implementations of the
CHAPTER 12
234
When you test the program, youll see text on your page and nothing else. The key to understanding the relationship between HTML5 and JavaScript is in the function: document. write(). The document refers to the Web page, and write() is a method that tells the Web page what to do. In this case, write() instructs the program to write the text in quotation marks to the Web page.
Save it as externalJS.js in a text-file format. Next, enter the following HTML5 program and save it in the same folder as the externalJS.js program. The key part of the page is the <script> tag thats used to specify the JavaScript program to use.
<!DOCTYPE HTML> <html> <head> <script src=externalJS.js></script> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>External JavaScript</title> </head> <body> </body>
FUNCTIONS
JavaScript functions are packages of code that are launched when called by the Web page. The advantage of functions is that you can use them to package code and make changes to add new content. The built-in write() function only requires that you enter some text for it print to the document (Web page). You dont have to rely on built-in functions but can create your own. For example, the following is an external JavaScript program with a simple function that opens an alert() function. (A user function using a built-in function.) Save the following JavaScript program as nameMe.js:
// JavaScript Document var name=Little Willie Hacker; function getName(someName) { alert(someName); } getName(name)
All functions are followed by parentheses. If required, the developer can put a parameter in the parentheses. In this case, the parameter is called someName. When the function is called, the developer places a name, a number, or anything else desired in the space where someName is. In this case, a variable labeled name is assigned the value Little Willie Hacker. At the bottom of the program, the line, getName(name) calls the function, placing the variable into the parameter. The function passes the value of the variable to the alert() function within the getName() function, so you can expect to see an alert box on the screen when the program launches. The following HTML5 (JSfunction.html in this chapters folder at www.wiley.com/go/smashinghtml5) calls the JavaScript that calls the function.
<!DOCTYPE HTML> <html> <head> <script src=nameMe.js></script> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>External Function</title> </head> <body> </body> </html>
235
That JavaScript program launched as soon as the page loads. A more important use of JavaScript functions lies in its ability to wait for the JavaScript until it needs it. The next section shows how.
PART IV:DYNAMIC HTML5 TAGS PLUS A LITTLE JAVASCRIPT AND PHP EVENT HANDLERS
The real power of JavaScript with HTML5 can be better seen when the program waits until the user does something to launch a script. For example, if the user clicks something, you can launch any JavaScript program you want. You use an HTML5 event handler. The page detects some kind of action (an event) and has a built-in function that recognizes the event. HTML5 recognizes a lot of events. Some of the events occur automatically such as when the page loads. Other events occur when users do something with the mouse or keyboard. The elements in Table 12.1 shows a sample of some of the different events handlers.
Table 12.1
onchange
For example,
<body onLoad = announceSomething()>
uses the body element with the onLoad event handler to fire a JavaScript function named announceSomething().
237
The JavaScript functions can be whatever you want them to be, which enables you to interact far more with the users. You can provide instructions, options, cautions, or whatever you want.
That kind of code is nothing new to HTML5. Its used here for one simple reason: When the mouse moves over the text within the <a> tag, the cursor changes so that users know that theyre over linked text. However, you can set up an event handler in any element. For example, consider the following Web page (ClickP.html in this chapters folder at www.wiley.com/go/smashing html5).
238
In looking at the above program, you may have noticed that some events are embedded inside other elements that also have event handlers. For instance, all the elements are inside the <article> tag. What will happen when you click on the paragraph that has an event
239
Figure 12-1: Nested event handlers.
In the top panel, as soon as a user clicks the line Click This Paragraph, the event is reported in the alert box (top panel). Then, when the user clicks the OK button in the JavaScript pop-up, the second alert appears letting him know that hes clicked in the <article> container as well. One way of looking at the events is bubbling up, beginning in the lowest level in the hierarch of elements and then bubbling up to the topmost level.
addresses a form named fred within a document. The HTML5 markup looks like the following:
<form name= fred>
Other times, youll see a built-in function that does something with the document such as,
document.write(This is straight from the Document);
which prints text on the screen. Also, the window root along with the document has several built-in functions that are useful for manipulating viewing areas of a Web page.
240
This page requires a second page to open as a separate window. The following (OtherWindow. html in this chapters folder at www.wiley.com/go/smashinghtml5) provides a page to open and, at the same time, the DOM-based script to close the open window.
<!DOCTYPE HTML> <html> <head> <style type=text/css> h1,h4 { font-family:Verdana, Geneva, sans-serif; color:#930; } a { text-decoration:none; color:#cc0000; text-align:center; } </style> <script type=text/javascript> function shutItDown() { window.close(); } </script> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>Other Window</title> </head> <body> <h1>This window has an important message. . . .</h1> <h4>Stand by while I figure out what it is. . . .</h4> <a href=# onClick=shutItDown()>Shut the window!</a> </body> </html>
241
Figure 12-2 shows what you can expect to see when the Web page opens as second window. Up to this point in the book, when one page has linked to another page, the current page has disappeared as soon as the user clicks a link. However, with this little JavaScript, you can talk directly to the page and tell it you want a new window of a specified size to open while your current window stays open.
243
The <form> tag has no information beyond the tag itself. For this application, it needs none. Within the <form> container, two input forms are named cost and tax. In the context of the DOM, each is an object with certain properties, one of which is valueAsNumber. Whatever number character is in the input form is treated as an actual number instead of a text character. The valueAsNumber is a property of the <input> tag and not the number type that was used in this example. (We couldve used a text value for the input type and had the same results using the <output> tag.) The number input form has a spinner type of input window, but values in the input window are not automatically converted into numeric data. Figure 12-3 shows the results of the Web page in an Opera browser (the only HTML5 browser that had implemented the onFormInput event handler at the time of this writing). Notice how the onFormInput event handler works. As information is entered into the form, the results are calculated and displayed. Initially, the result is NaN (Not a Number) because the tax entry is null, resulting in a non-number result. However, as soon as the tax is entered, the output changes to a number.
Figure 12-3: Using the <output> tag for calculations in Opera browser.
244
VARIABLES
A variable is something that changes it varies. You can think of a variable as a box with a label on it. For example, you might have a box with the label MobilePhone. In the box, you can place only one thing. You can change whats in the box what we call the boxs value. So, if you have iPhone in your MobilePhone box, you can take it out and put in either a different iPhone (a newer model) or a different phone such as an Android. Now, the box has a different value. The label-value pair (or name-value pair) is the combination of the variables label and its current value. You dont have to put in the name of a mobile phone in the MobilePhone box. You can put in anything you want a tin-can walkie-talkie or a pink elephant. Assign whatever value you want and any type of value, including another variable. If I wanted, I could put in a number a real number, not just one that identifies something such as a street address. However, a good and practical practice is to use variable names that can be associated with what you expect to
creates a variable named billVar. It then assigns it the value Brought to you by Bills variable. When the variable is placed in the alert function, notice that no quotation marks surround the variable.
Types of data
When you assign values to a JavaScript variable, you can assign any kind you want and then change it to a different type. First, though, you need to have an idea of the different types of data that are available. The following list provides a brief description of each:
String: Treated as text, typically in quotation marks Number: An actual number (integer or real) that responds to math operations Boolean: A two-state (true or false, 0 or 1) data type Function: A set of JavaScript operations contained in a module Object: An encapsulated collection of properties (variables/arrays) and methods (functions)
245
Youve seen how string variables work. When you put numbers into a string, theyre treated as text instead of numbers. For example, the following string treats the 123 exactly like Elm Street as text.
funHouse=123 Elm Street;
Likewise, if you used the following assignment, youd still have text and the results would show it:
firstNumber=123; secondNumber=7; total=firstNumber + secondNumber; document.write(total);
Instead of showing 130 the results show 1237. Next try the following:
firstNumber=123; secondNumber=7; total=firstNumber + secondNumber; document.write(total);
246
Depending on the type of computer you use, the browser variables value will be different. (It certainly varies.) The page was run on both a Windows 7 and Macintosh computer to see how one variable varied. Figure 12-4 shows the different output from the same program.
247
The variable value, navigator.platform is an object. The navigator object has a property, platform, that tells what type of computer the browser is running on. In testing the program in Windows 7 (refer to the top panel in Figure 12-4) with a 64-bit operating system, the results show Win32. Thats because the browsers tested were 32-bit, including an early version of Internet Explorer 9. The MacIntel results (refer to the bottom panel in Figure 12-4) were on a Macintosh computer with an Intel processor displayed on an Opera browser.
PART IV:DYNAMIC HTML5 TAGS PLUS A LITTLE JAVASCRIPT AND PHP ARRAYS
A variable can have only a single value at one time. The value can be a computed based on a combination of different values, but once its stored inside a variable, it becomes one. For instance, as shown in the previous section on variables,
firstNumber=123; secondNumber=7; total=firstNumber + secondNumber;
The variable named total is the sum of the first two variables. It is a single entity. This would be true were they concatenated as well. So, just remember: Variables can have only one value at a time. Figure 12-5 provides a graphic illustration of the difference between variables and arrays.
Variable
Array
248
stuff[0]
stuff[2]
stuff[3]
As you can see in Figure 12-5, only a single item is stored in the variable named TrueLove, but the array, stuff, has lots of, well, stuff. You call each one of the stored datum with the array name with a number in braces. So, stuff[1] is an anchor and stuff[2] is a calculator. Some applications require multiple values in a single object, making it easier to recall and store data. Each value in an array is called an element. You reference each by a number, beginning with zero (0) and numbered sequentially (refer to Figure 12-5). Suppose you have an array named fruit. You might assign values as shown here:
<!DOCTYPE HTML> <html> <head> <script type=text/javascript> fruit=new Array(); fruit[0]=rasberries; fruit[1]=peaches; fruit[2]=apples;
The result of the preceding program are the words peaches, plums, and 3 on the screen. Peaches was pulled out of the array by number reference and placed into a screen output function. Then using the pop() method, the element on the top of the array was placed into a variable named myFruit and displayed to the screen. Finally, the pop() method removed one element from the array and placed it into the myFruit variable, so now the array has a length of 3 and thats whats shown on the screen. Each element in an array works just like a variable. The difference is that its part of a larger object the array.
OBJECTS
The final data type used to store values is an object. (Wasnt the Array an object? Yep. Youre already ahead of the game!) All objects are similar to arrays in that they can hold more than a single value. However, objects have several built-in properties. The properties have either fixed values (called constants) or values that change depending on the circumstances. Even the Array object has a built-in property length. It returns the number of elements in the array. So, if you add the following two lines to the array program in the previous section, youll see how big the array is:
... document.write(fruit[1]); //Add the following two lines document.write(<br>); document.write(fruit.length);
249
The value of fruit.length is 4 its always one greater than the highest-numbered array element because the length is the actual number of elements in the array beginning with the value 1. (Its one-based instead of zero-based.) Some properties of objects are called methods. A method is a function that does something in relation to the object. For example, an Array object method is pop(). The pop() method returns the last element in the array. Its a way that you can assign a variable an objects method just as you can assign a variable a function. Lets fix up that program from the last section again. This time, the variable myFruit is assigned fruit.pop(). That means whatever is on the top of the array stack is removed. However, if used in a variable assignment, it assigns the removed element to the variable as the following fix-up of the previous snippet shows:
When you test the program from the previous section with the above changes, youll see that the last added element has a value of plum, and thats what is printed to the screen. However, the length is no longer 4, but now 3. Thats because the pop() method removes the element from the array. (By the way, the var in front of the myFruit variable is optional to declare a variable, but it helps to distinguish it from the array elements in this listing.)
250
Next, to add a property, you invent a new name for the property and assign it a value. The object name and its property are separated by a dot (.). For example, the following adds a property named firstNumber and assigns it a value of 4:
AddingMachine.firstNumber=4;
Just like a variable, you can change the firstNumber value to something else. To add a method (a function) is just as easy. However, instead of using a named function, you use an anonymous one. For example, the following adds the value of two properties for the AddingMachine object and sends them to the screen:
AddingMachine.total=function() { document.write(this.firstNumber + this.secondNumber); }
The keyword this is a reference to AddingMachine. Its the same as writing Adding Machine.firstNumber. Notice also that function() has no name its anonymous.
Note that the method AddingMachine.total() uses the method document.write(). (You can spot methods in JavaScript by looking for the parentheses.) Also, note that to fire off the method, the name of the object and function are listed and off it goes. When you test it, youll see that the results are the total of the two properties.
251
History Location
For example, in the Types of data section earlier in this chapter, you saw how the navigator.platform property was used to find the type of computer in use.
The HTML5 DOM itself has far more objects, and the most used is the Document property. The list of objects is the same as the list of elements. So, a list of all the DOM objects is a list of all elements, plus some others that are used in conjunction with the DOM. For example, the following are included in the HTML5 DOM but arent exactly elements:
252
Some of these objects we see in tags. For example, the image object is seen in the <img> tags. Its properties are similar to the img elements attributes. Others, like document are implied in that a Web page is the document. The event object is employed in event handling with methods such as onClick. The rest are elements, so they should be familiar. But instead of attributes in a tag, expect to find properties with the same names and functions as equivalent attributes.
SMASHING HTML5
13
ONE OF THE most important additions to HTML5 is the <canvas> tag. With it, you can draw just about anything on an HTML5 page. With just two attributes, width and height, theres not a lot to remember about attributes. However, the canvas element is implemented in what might be called a Document Object Model (DOM) style. Chapter 12 describes the DOM in detail. Essentially, DOM style means writing the required JavaScript with references to objects and their methods and properties. If that kind of talk has you quaking in your flip-flops, relax. Throughout the book, the HTML5 tags (elements) have used attributes, and attributes are just properties of the elements. For
CHAPTER 13
CANVAS BASICS
Because the canvas element is a crucial part of HTML5 and works only with HTML5compatible browsers, the first thing you want to do is to let users know that they need an HTML5 browser. Several methods are available to find out whether canvas works with their browser, but the easiest and most informative (to the user) is to place a message in the <canvas> container. Only users without HTML5-compatible browsers see the text in the container. For example, the following line, easily mistaken for the outcry of a drama queen, gets the message across. At the same time it remains invisible to users who have HTML5 browsers:
<canvas id=colorScheme width=600 height=100 >Come on, Jack & Jill! You <i>really</i> need to get an HTML5 Compatible browser. Youre missing <b>canvas!</ b></canvas>
I dug up an old (really old!) Internet Explorer browser for the Mac. Figure 13-1 shows what appeared when I opened the page with the <canvas> tag.
254
Just to be fair, I ran the same program in an early (really early!) version of Internet Explorer 9. As you can see in Figure 13-2, the canvas drawing appears, but the message does not.
255
Not only will the non-HTML5 viewer get the message about updating his browser, but hell get it in the style described in CSS3. Hell also be able to view both the picture and the caption, as shown in Figure 13-3. If you do use an HTML5 browser, the preceding program presents a big blank green screen with nothing on it. So, be sure that if youre using an alternative for non-HTML5 browsers, you have something actually in canvas.
256
This should be pretty familiar. The width and height were simplified to equal 100 pixels, and the new name of the canvas object is redHot. Ive already covered the closing </canvas> tag and message in the container. And the rest of the work is all JavaScript programming working with the DOM. As noted earlier, Im going to try to simplify things by using a little OOP in the JavaScript to reflect the programming structure of the DOM. So, the first task is to create an object and a method for it.
CanvasMaster=new Object(); CanvasMaster.showCanvas=function()...
257
As you saw in Chapter 12, all that does is set up an object and a method for the object a function that will call the JavaScript operations when we need it. Next, the program needs a way to access the canvas DOM node. Thats the part of the DOM that has canvas and canvas-related methods and properties. The first step is to create an object that holds the DOM node. Instead of thinking of assigning a node to a variable, think of it as creating an instance of an object that has the properties and methods of the canvas object.
canvasNow = document.getElementById(redHot);
That line creates an object that contains the canvas object named redHot. Once we have an instance of a canvas object, the program needs a rendering context. About the only context available is one called 2d, suggesting a two-dimensional drawing context. The canvas object (canvasNow) has a method called getContext() to do what it says: get the rendering context.
contextNow = canvasNow.getContext(2d);
The fillStyle property is only for the fill color and not the stroke (outline) of the object. Next, the fill color needs a shape to fill. To fill a rectangle, use the following: 258
contextNow.fillRect(5,20,100,100);
To explain everything in that last piece of code, Figure 13-4 breaks it down.
X position Width
Height Y position
The first two values place it within the canvas area not the whole Web page and the second two values specify the width and height of the rectangle. The last requirement is actually to carry out filling the rectangle with the specified color. The next line performs that task:
contextNow.fill();
No matter how many operations are defined, a single fill() method takes care of all the fills defined in the larger method.
contextNow.fillRect(5,20,100,100); // x, y, width, height contextNow.fill(); } </script> <style type=text/css> body { font-family:Verdana; color:#cc0000; } </style> <title>Red Square</title> </head> <body onLoad=CanvasMaster.showCanvas()> <figure> <canvas id=redHot width=100 height=100 > Youre missing the Red Square! Get HTML5, comrad! </canvas> <figcaption> <br/> Red Square </figcaption> </figure> </body> </html>
259
As you can see, the program includes CSS3 and a simple caption along with the appropriate <figure> and <figcaption> tags surrounding the <canvas> tag. The results of this script are shown in Figure 13-5. Notice that the script also contains a message for non-HTML5 browsers, but because Figure 13-5 shows the canvas image, the browser will not display any content in the <canvas> container.
260
contextNow.fillRect(405,20,100,100); // fifth color contextNow.fill(); } </script> <style type=text/css> body { font-family:Verdana; color:#570026; } </style> <title>Feel Like a Tortilla!</title> </head> <body onLoad=CanvasMaster.showCanvas()> <figure> <canvas id=totillaHues width=500 height=120 > No tortillas for you! Get your HTML5 browser...pronto! </canvas> <figcaption> <br/> Tortilla Flat </figcaption> </figure> </body> </html> // fill all!
The important parameters in this script are the first two in the fillRect() method. Theyre the x and y positions, and no two squares can be in the same space. The squares are lined up in a horizontal row, so all you need to pay attention to is the x-value because the vertical position is going to be the same. Once all the fillStyle() and fillRect() methods are laid out, the drawings require only a single fill() method to display them all. Figure 13-6 shows how the figure looks on a mobile Safari browser on an iPhone.
261
262
{ canvasNow = document.getElementById(strokeAndChomp); contextNow = canvasNow.getContext(2d); contextNow.fillStyle = #ACCFCC; contextNow.fillRect(5,20,100,100); contextNow.fill(); } CanvasMaster.addStroke=function() { contextNow.strokeStyle=#595241; contextNow.strokeRect(7,22,91,76); } CanvasMaster.chomp=function() { contextNow.clearRect(5,20,100,100); } CanvasMaster.punchOut=function() { contextNow.clearRect(40,45,30,30); } </script> <style type=text/css> body { font-family:Verdana;
263
This page is formatted for a mobile device. It was tested in Opera Mini on an iPhone, as shown in Figure 13-7. A blue square appears on the initial load. When you add a stroke line, a frame appears just inside the original image. If you add more strokes, youll find that the stroke darkens. When you click the Punch Hole selection, a small square appears in the middle of the blue square. The Gobble Up Square selection removes both the image and the stroke. If you click the Add Stroke text after having removed the blue square, youll see the stroke line only with no blue rectangle.
264
The reference to the file that youre loading: In this case, the label pic is the reference name to the file being used. The x and y position: Its a little more involved than using the <img> tag, but not much, and this method lets you place the image where you want it within the canvas parameters. The source of the image: You add the source of the image within the method that creates the rendering context not unlike the identification using the img element.
The color can be assigned using any of the methods discussed in Chapter 4. The shadow offsets depend on how big you want your shadow. Experiment with different values, beginning with about 5. In the following example, each is set to 10 to provide enough shadow to make the image rise off the screen but not so much to overwhelm the image. Finally, the blur value can be greater or smaller depending on both the offset values and the amount of blur you want. With greater offset values, you need greater blur values. To make the shadow have an effect on the image, all shadow properties must be entered before writing the drawImage() method. Thats all there is to it. The other JavaScript to set up the canvas context rendering is very similar to the drawings in the previous section. The following code (PhotoShadows.html in this chapters folder at www.wiley.com/go/ smashinghtml5) loads the image and places the drop shadow on it:
<!DOCTYPE html> <html> <head> <script language=javascript> //colors: F4F1BC,736F36,BFB95A CanvasMaster=new Object(); CanvasMaster.showCanvas=function() { canvasNow = document.getElementById(picFrame); contextNow = canvasNow.getContext(2d); pic = new Image(); pic.onload = function()
265
266
Before putting in your own images, check their size and the size that the <canvas> tag has reserved. In this case, there was enough room for both the image (a photograph) and the graphic drop shadow. Figure 13-8 shows the results in a Google Chrome browser. The color combinations used with the image are important. Youll find that some colors work better than others. The ones used in Figure 13-8 are a monochromatic set based on the colors in the image. As you can see, the shadow nicely lifts the photo off the screen. Compare the image in Figure 13-3 with the one in Figure 13-8. In Figure 13-3, you see what happens with non-HTML5 browsers; in Figure 13-8, what HTML5 browsers can display. Also, in this latest use of the same digital photo, the non-HTML5 browsers see only the message that theyre not seeing the image. If you want, you can add the same image and color scheme without the drop shadow for non-HTML5 browsers.
267
Instead of using a hexadecimal value, it uses RGB with an alpha channel rgba() that controls for transparency. The last parameter is a value between 0 and 1. The higher the value, the more opaque the image will be. By using a value less than 1, you can control the degree of opacity. The rest of the shape matches the dimensions of the image and is positioned in the same space. To integrate an image with the rest of the page the plan is to add a color tint using the background color. The following program (FilterImage.html in this chapters folder at
268
</script> <style type=text/css> body { font-family:Verdana; color:#F26A4B; background-color:#F2D091; } </style> <title>Filtering Images</title> </head> <body onLoad=CanvasMaster.showCanvas()> <article> <figure> <canvas id=filterFrame width=472 height=306 > Not only do you miss the filtered image, but you miss the dance! Get an HTML5 browser! </canvas> <figcaption> <br/> Filtered Image</figcaption> </figure> </article> </body> </html>
Notice that the sequence first loaded the image and then placed the drawing on top using the following snippet:
If the drawing is added first, the image simply sits on top of it as though no filter at all is used. Now, with the added filter, the image better fits in with the page, as Figure 13-9 shows.
269
Using Adobe Photoshop or some similar image-editing software, you couldve added the filter to the image and loaded the filtered image with a standard <img> tag. However, using canvas and HTML5, you can make the changes without any additional software.
context.beginPath() context.moveTo(x, y) context.closePath() context.lineTo(x, y) context.quadraticCurveTo(cpx, cpy, x, y) context.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) context.arcTo(x1, y1, x2, y2, radius) context.arc(x, y, radius, startAngle, endAngle, anticlockwise) context.rect(x, y, w, h) context.fill() context.stroke() context.clip() context.isPointInPath(x, y)
Knowing how to use these methods with a <canvas> tag doesnt ensure that theyll look good. The remainder of this chapter examines most of these methods. You should be well on your way to creating many different shapes by the chapters end.
The grid boxes are 20 pixels wide and 20 pixels high. If you take a pencil and a piece of grid paper (or turn on the grid on a drawing program), you can replicate the images in Figure 13-10. Starting with the left image in Figure 13-10, a typical drawing would consist of the following steps:
271
272
Figure 13-11 shows what you can expect to see. (If you worked out the coordinates on your own, yours probably looks better!)
In looking at Figure 13-12, you can see that the outline and color are correct, but instead of a handle theres a block. Whenever a series of drawing methods are used without beginning a new path, and then when the context.fill() method is called, it fills it to the beginning of the path. As a result, everything is filled and not just the parts you want. To fix this, two context.fill() methods are employed. One is at the end of the first outline of the briefcase, and the second is at the end of the outline for the handle. The first is filled with brown, and the second is filled with white. Additionally, a second context. beginPath() is added at the beginning of the drawing of the handle. The following program (SimpleLineDrawingFilled.html in this chapters folder at www.wiley. com/go/smashinghtml5) has all the code revised to generate the filled image.
<!DOCTYPE html> <html> <head> <script language=javascript> //colors: 960, fff, 000 CanvasMaster=new Object(); CanvasMaster.showCanvas=function() { canvasNow = document.getElementById(briefCase); contextNow = canvasNow.getContext(2d); contextNow.beginPath(); contextNow.moveTo(40,20); contextNow.lineTo(72,20); contextNow.lineTo(72,38);
273
274
When you test this revision, the results are pretty close the original drawing. Compare Figure 13-10 and Figure 13-13 to see how close the program-generated image is to the original. You can use the lines to draw anything that has no curves. In the next section, youll see how to add curves to your artistic canvas tools.
CURVES
Making curves, even with drawing tools, is trickier than drawing straight lines. To understand how to make curves, Ill start this section with a discussion of arcs and the canvas DOM methods for creating them. Well look at some of the geometry, but not a lot. (You do need a little understanding of geometry, but dont worry its basic.) The first thing that you need to understand is the difference between degrees and radians. Most people know that a circle has 360 degrees. On a compass rose, 360 or 0 degrees (12 oclock) is due north. As you move clockwise to 90 degrees (3 oclock), the compass points east; at 180 degrees (6 oclock), south; and at 270 degrees (9 oclock), west. However, you have to use radians instead of degrees, so all degrees must be converted to radians. Use the following formula: Radians = (PI 180) degrees So, lets say that you want to know the radians for due west (9 oclock), 270 degrees: Radians = (3.14159265 180) = 0.01745329251994 Radians = 0.01745329251994 270 Radians = 4.71238898 A simple way to do the same thing is to just multiply degrees by 0.01745329251994 or in JavaScript write:
radians = (Math.PI/180)* degrees;
275
Arcs
The canvas DOM method for drawing arcs is context.arc(). The method has several parameters that need to be understood in concert and individually:
x,y: Circles center radius: Radius of circle startAngle: Start point of arc expressed in radians endAngle: End point of arc expressed in radians anticlockwise: Boolean (true is counterclockwise and false is clockwise)
I find it helpful to envision either a compass rose or a clock with the four cardinal directions and time/degrees north (12 oclock or 0 degrees), east (3 oclock or 90 degrees), south (6 oclock or 180 degrees), and west (9 oclock or 270 degrees). A full arc statement looks like the following:
contextNow.arc(150,100,50,six,0,true);
276
This arc has its center at x = 150 and y = 100, and it has a radius of 50. The start angle is set to 6, which is a variable that weve created to represent the 6 oclock position of 180 degrees. The variables value has been converted to radians. Both degrees and radians have the same value at the 12 oclock position (0), and it is used as the ending angle. Finally, the arc is set to true anticlockwise. This next program is one used to experiment with different arcs. Four variables 12, 3, 6, and 9 are set in radians corresponding to the positions on a clock. Certain statements are commented out but will be used later.
<!DOCTYPE HTML> <html> <head> <script type=text/javascript> CanvasMaster=new Object(); CanvasMaster.showCanvas=function() { canvasNow = document.getElementById(beHappy); contextNow = canvasNow.getContext(2d); contextNow.beginPath(); contextNow.moveTo(0,0); contextNow.lineTo(300,0); contextNow.lineTo(300,200); contextNow.lineTo(0,200); contextNow.closePath(); contextNow.stroke();
277
The RADCON variable is a constant ( 180), so all degrees were set to radians by multiplying their values by RADCON. As noted, the variable names represent the positions on a clock. In addition, a rectangle around the area where the arc is drawn represents the boundaries of the <canvas> tags width and height. Figure 13-14 shows the result. The starting point of the arc is on the left, and it moved anticlockwise to the ending point on the right. Change the following line:
contextNow.arc(125,100,50,six,twelve,true);
to:
contextNow.arc(125,100,50,six,twelve,false);
That changed the drawing from anticlockwise to clockwise, but it made a major difference, as youll see when you test it. 278 Next, using the same program, change the line back to:
contextNow.arc(125,100,50,six,twelve,true);
Then remove the comment lines (//) from the following line:
//contextNow.closePath();
And test it again. The final change to the program will fill the arc. Uncomment the line from the following:
//contextNow.fill()
to this:
contextNow.fill()
When the changes are made, your arc now looks like a kettle, as shown in Figure 13-15.
The only way to really learn to work with arcs is to practice with them. Use the script in this section to try different things.
279
To create a gradient fill, both linear and radial, is fairly straightforward. The first step is using the canvas DOM context.createLinearGradient() method. The method expects four parameters: x0, y0, x1, y1. The gradient fill moves from x0 to x1 and from y0 to y1. A straight linear gradient from left to right would have a single value in x1, and the rest would be 0. A gradient from top to bottom would have value in either y0 or y1, with the rest set to 0. To set the gradient colors, use the gradient.addColorStop() method. It expects two parameters. The first is a zero-based number from 0 to 1 and the second is the color. Once thats completed, assign the context.fillStyle the gradient. The following snippet shows the steps in adding a gradient fill:
sunsetGradient=contextNow.createLinearGradient(0, 0, 0,379);
In this particular example, the gradient is a vertical one. The first color, yellow, is at the top, and the second color, red, is at the bottom. Putting it all together, the following script (Sunset.html in this chapters folder at www.wiley.com/go/smashinghtml5) creates a sunset for you.
<!DOCTYPE HTML> <html> <head> <script type=text/javascript> CanvasMaster=new Object(); CanvasMaster.showCanvas=function() { canvasNow = document.getElementById(sunset); contextNow = canvasNow.getContext(2d); sunsetGradient=contextNow.createLinearGradient(0, 0, 0,379); sunsetGradient.addColorStop(0, yellow); sunsetGradient.addColorStop(1, #cc0000) contextNow.fillStyle = sunsetGradient; contextNow.beginPath(); contextNow.arc(200,200,150,0,Math.PI*2,false);
280
}
contextNow.closePath(); contextNow.fill() </script> <style type=text/css> body { font-family:Verdana, Geneva, sans-serif; color:#cc0000; } </style> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>Sunset</title> </head> <body onLoad=CanvasMaster.showCanvas()> <figure> <canvas id=sunset width=400 height=400 > A shame you cant see the beautiful sunset because you dont have an HTML5 browser. Aloha... </canvas> <figcaption> <p>Sunset</p> </figcaption> </figure> </body> </html>
When you test the page, youll see a big circle with a yellow-to-red gradient. You can use the same gradient technique with other shapes as well. Figure 13-16 is displayed in the mobile version of Safari on an iPhone.
281 Theres far more that you can do with canvas, and one of the best features of images created using canvas DOM objects is that they arent as expensive (they dont take as much bandwidth) to load as bitmapped graphic files. Weve only skimmed the surface of this new powerful element in HTML5.
In Figure 13-13, you see two line objects a briefcase and a house. See if you can draw the house using the methods employed for creating the briefcase. Take an image of a picture frame, and superimpose another image that appears to be in the frame. (This project requires you to fix the frame and image sizes so that one will fit in the other.) Find or create a digital photo and superimpose a sunset on top of it. (Alternatively, create an image with another kind of gradient and superimpose it on a digital photo or other image. What about a gradient filter?)
SMASHING HTML5
14
ADDING FORMS
ONE OF THE most important features of any Web page is its ability to interact with a person. In computer science lingo, theres a subfield called human computer interface, which treats humans as another type of interface like a printer, USB drive, or Webcam. This doesnt dehumanize
people using computers. Instead, it treats people like something theyre not, and thats bound to get you in trouble sooner or later. This chapter shows both how to add interactive forms and treat people like people.
CHAPTER 14
ADDING A FORM
Forms are really in two parts (even more in some cases). The first part is the <form> tag that sets up a container for different kinds of input. The typical form can be envisioned as the following: Begin Form Input 1 Input 2 Input 3 Input 4 End Form So in discussing forms, were really talking about the form and its attributes and input elements and their attributes. With HTML5 forms, youll find plenty of new attributes and elements. Just so that you dont get bored, the following (degree2radians.html in this chapters folder at www.wiley.com/go/smashinghtml5) is an example of a simple calculator for converting degrees into radians (see Chapter 13 for a practical use for the converter). Just enter the degrees you want converted, and youll be presented with the equivalent radians. 284
<!DOCTYPE HTML> <html> <head> <script type=text/javascript> FormMaster=new Object(); FormMaster.resolveForm=function() { const RADCON=Math.PI/180; degreesNow=document.converter.degrees.value; radiansNow=degreesNow * RADCON; document.converter.radians.value=radiansNow; } </script> <style type=text/css> /*048ABF,049DBF,F2F2F2,595959,0D0D0D */ h3 { font-family:Arial Black, Gadget, sans-serif; color:#595959; } body { font-family:Verdana, Geneva, sans-serif; color:#049DBF; background-color:#0D0D0D; } </style> <meta http-equiv=Content-Type content=text/html; charset=UTF-8>
If youre at all familiar with forms in HTML, you know that this form is different it has a number input that treats the entries as real numbers instead of text that has to be converted to numbers by JavaScript. That wasnt available in older versions of HTML. Figure 14-1 shows the number spinners that appear in Opera when Web pages use the number input.
285
As youll see in this chapter, much is new, and using JavaScript and (later) PHP, you can do a great deal with HTML5 forms. So, prepare to find a good deal of new features and reasons to update your browsers to HTML5.
PART IV:DYNAMIC HTML5 TAGS PLUS A LITTLE JAVASCRIPT AND PHP GENERAL FORM ATTRIBUTES
The form (think the mother ship) has several attributes that impact every input element in the form container. However, the first focus is on the form itself. It has the following attributes:
Many of these attributes are rarely used and some only make sense when you start using programs like PHP and ASP.NET where you pass data to and from a database. However, well examine them all.
If no character encoding is assigned, it is assumed to be unknown and uses the default character encoding. When using multiple encodings, each is separated by a space in HTML5 instead of by commas and semicolons as in earlier versions of HTML. Most of the time, the enctype attribute is left blank and uses the default state. The enctype attribute has three keywords and states (keyword/state):
A form may be set up to accept plain text and would be assigned the following:
<form enctype=text/plain>
For the most part, though, this is another attribute that is not included in the <form> tag. Thats because the default (urlencoded) is what you want.
That effectively blocks submission validation. A better solution lies in the Boolean formnovalidate and required attributes that can be placed in individual input elements. For example, the following form has no validation for a cancel button and the middle name is not required, although the first and last names are.
<form name=motherShip accept-charset=utf-8> First name: <input type=text name=fn required> <br> Middle name: <input type=text name=mn > <br> Last name: <input type=text name=ln required> <br> <input type=submit name=submit value=Send the info!> <input type=submit formnovalidate name=cancel value=Cancel> </form>
287
The accept-charset, enctype, and novalidate attributes arent ones youre likely to use too much. However, the input element attributes for requiring data entry and nonvalidation can be quite handy.
In Chapter 16, youll find that both of these attributes are always used when dealing with PHP.
Autocomplete
A fairly simple but important form attribute is autocomplete. It has two states, on and off, and it defaults to on. Basically, if you do not want autocomplete, just set it to off. Otherwise, its the default state of forms. Sometimes autocomplete can be a bother; if so, just add the following line:
<form autocomplete=off>
With the state set to off, a reused word will not pop up. For example, if you change your e-mail address, your old address may show up automatically in e-mail address boxes if the autocomplete is not set to off.
288
The text input element can be anywhere on the page, and that means designers dont have to put all the input in one place. Try the following script (FormID.html in this chapters folder at www.wiley.com/go/smashinghtml5) and test it with Opera (which has implemented this new feature).
<!DOCTYPE HTML> <html> <head> <script type=text/javascript> FormMaster=new Object(); FormMaster.resolveForm=function() { favorite = document.formName.favURL.value; personName=document.formName.person.value; message=personName + s favorite Web site is +favorite; document.formName.output.value=message; } </script> <style type=text/css>
289
Notice that inside the <form> container with the name=formName and id=formID is a single input element, a <textarea> tag and a Submit button. More important, though, notice that the input element with the name=favURL is outside of the form container. However, it assigns itself the id of the form on the page formID. In HTML5, its treated as though it were inside the <form> container. Figure 14-2 shows that the data entered in the
290
Now, you dont have to worry about where you put your input forms. As long as input elements are assigned the form ID of the form, theyre treated as though theyre inside the form container. The target attribute refers to the browsing context of the form upon form submission. If no target value is assigned, the browsing context is the same as if _self were assigned to a target attribute. The other browsing contexts are _blank, _parent, or _top. The _blank browsing context is quite helpful where you have information from a server-side script that replaces the content on the calling page with its own content. Using _blank enables users to see both the calling page and the information from the called page.
To help see the parts in a DOM arrangement, the following simple script (NameID.html in this chapters folder at www.wiley.com/go/smashinghtml5) demonstrates different ways of referencing the same objects in a document with forms. The preferred manner is by object and property name. The different combinations are for demonstration only. It also uses several types of input as well.
<!DOCTYPE HTML> <html> <head> <script type=text/javascript> FormMaster=new Object(); FormMaster.resolveForm=function() { alpha = document.motherShip.elements[0].value; beta = document.forms[0].secondInput.value; gamma = document.motherShip.thirdInput.value; delta = document.forms[0].elements[3].value; epsilon = document.motherShip.fifthInput.value; const cr=\n; message=alpha+cr+beta+cr+gamma+cr+delta+cr+epsilon; document.motherShip.output.value=message; } </script> <style type=text/css> h3 { font-family:Arial Black, Gadget, sans-serif; color:#677E52; } body { font-family:Verdana, Geneva, sans-serif; color:#89725B; background-color:#B0CC99; } </style> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>DOM and Forms</title> </head> <body > <article> <header> <h3>DOM, the Form, and the Nodes</h3> </header> <form name=motherShip> <input type=number name=firstInput> Number<br> <input type=email name=secondInput>
291
When you test the program, enter the appropriate text and numbers and them click the button, Send to DOM. In the JavaScript program, notice that as long as either the element names or their proper element name (or node name) is used, the entered materials are sent to the text area that is used for an output display. Figure 14-3 shows the results you can expect to see.
292
The contents are retrieved through the DOM paths and placed into variables and then sent to the <textarea> element for display. Between the five elements a constant (const cr=\n) places a control character to force a line feed.
Table 14.1
Type Value
Type Value
Features
Selection Date picker Date picker File upload Image coordinates Numeric value Selection Clears entries Send form data String value Web address
button color* datetime* email hidden month* password range* search* tel time* week*
*New to HTML5
checkbox date* datetime-local* file image number* radio reset submit text url*
293
At the time of this writing, not all these types have been implemented in the major browsers. However, because browsers keep working to fully implement the new HTML5 standards, dont be afraid to experiment on your own with different types. Now for the general input attributes (including type!) in Table 14.2.
PART IV:DYNAMIC HTML5 TAGS PLUS A LITTLE JAVASCRIPT AND PHP Table 14.2
Input Attribute
Input Attribute
Features
Hint of le loading Sets focus to eld Unusable Form override Form override Form override Datalist suggest Maximum length Multiple values Regular expression Cannot input Num char visible Number of steps Assigned value
accept autocomplete* checked form* formenctype* formnovalidate* height* max* min* name placeholder* required* src
alt autofocus* disabled formaction* formmethod* formtarget* list* maxlength multiple pattern* readonly size step* value
294
type width*
*New to HTML5
With all the different combinations of attributes and their values, the next several sections take a look at different groupings of form-related elements, attributes, and values in combinations. The first section covers using the datalist element with the list and form attributes. As with all the following sections, this one packs in as many features as possible while still focusing on the key features under discussion.
295
In looking at the script, you may be wondering what the label attribute is doing in the <option> tag in the <datalist> container. Theres no label attribute in either the form or input element (see Table 14.1 and Table 14.2). Thats because the label attribute is not in the form or input elements, but in the <option> tag. Although that may seem obvious, when you open the page, you see not only the URLs but also the label in the URL input window. Whats happening is that the <input type=url> tag holds a reference to the data lists options through the list attribute in the input elements markup. At the time of testing, the data list shows up in Opera using either Windows 7 or Mac OS X. In the top-left panel, you can see the selections available in the data list (along with a label for each). Once the user makes a selection, it appears in the input window as shown in the top-right panel. Finally, in the bottom panel, you can see that its passed to the JavaScript function that displays it in an alert window. (Note that the Opera alert window also displays the domain.) The important point about this process is that users dont have to type in URLs. Everyone who has ever typed in a URL has made a typo at some point. By using the data list to help out, not only is the suggested URL more likely to be selected, but its easier for the user.
296
Figure 14-4: Special mobile device keyboard for URL form (left) and standard mobile keyboard (right).
297
298
299
Although thats a bit long, most of it was formatting so that it looks halfway decent and its easy for users. The <fieldset> tag was used to highlight a group of buttons and to encapsulate the output window. Its a great tag to use when you want to group elements. The <legend> tag allows you to place a label in the enclosing rectangle around the field set. Figure 14-5 shows what you can expect to see when you load the page. 300
DATE PICKER
The last input attribute we have space to cover in this chapter is simple to implement but has impressive results. The new date attribute for the input element is powerful and easy to include in a form. Several new date and time attributes have been added to the input element, but only the date attribute itself is shown. The following program (Pickers.html in this chapters folder at www.wiley.com/go/smashinghtml5) shows you how to set it up and use it to send information.
<!DOCTYPE HTML> <html> <head> <script type=text/javascript> FormMaster=new Object(); FormMaster.resolveForm=function() { alert(document.calendar.dateNow.value); } </script> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>Date</title> </head> <body > <form name=calendar> <input name=dateNow type=date onChange=FormMaster.resolveForm()> </form> </body> </html>
301
With just that little markup in the form container, youre able to build a complete calendar. You can use the onChange event handler to capture the date selected from the calendar. Figure 14-6 shows the application in an Opera browser (the only one found to work so far with this new input attribute) in a Windows 7 environment. In this particular implementation, as soon as the user makes a selection, the alert window opens and shows the selected date, as shown in Figure 14-7. The purpose is to show how easy it is to pass the selected date value. Such data could be stored in a database to make online reservations.
302
The little window behind the alert window shows the selected date in a small window. (The little window shows the selected date with no other required programming.) The importance of this new HTML5 feature lies in the ease with which users can select a date. If youve ever worked with a similar tool in making airline or hotel reservations online, you know how valuable it is. The only problem at the time of this writing is that no other HTML5 browser other than Opera includes it.
You need to use JavaScript (at this stage) to access data that would generally be passed on to a server-side program like PHP, ColdFusion, or ASP.NET. However, to simulate that, the examples in this chapter have used a button input type to fire a JavaScript program that sends the results to a <textarea> where you can see what would normally be sent to the back end for processing. Heres the challenge:
Devise an online store that sells a line of products (at least five) or delivers services (again, at least five). Examples would be a computer store or a Web design service. Design an interface where users enter their name, e-mail, URL, address, city, state, zip code, and a username and password, with as little effort on their part as possible. To make it bulletproof, test it with someone whos never seen it before. Users then select several products or services (again with as little effort on their part as possible). The selected offerings are then displayed in a <textarea> with their corresponding individual prices along with appropriate tax. The program also generates a shipping label. It will just be displayed in the <textarea> not printed out.
303
The more form elements and attributes that you can use that were not discussed in the chapter, the better.
SMASHING HTML5
15
FOR YEARS, USERS have been able to do some pretty remarkable things on the Web thanks to different kinds of plug-ins loaded inside the browser. Generally speaking, two key plug-ins are installed with most browsers: Adobe Flash Player and Java. Some of the new HTML5 features work best in concert with either special plug-ins directly
CHAPTER 15
GEOLOCATION
The geolocation object is part of the navigation object in the HTML5 DOM. Its a means of finding your location, more or less. In several tests, it successfully located the ballpark of my location. The most important attributes of the geolocation object are the latitude and longitude attributes. Thats because, with those values, you can load a map of your general location. Creating an HTML page that shows users their latitude and longitude is fine, but HTML5 browsers are also able to load a map into their Web sites using Google Maps. The URL for this capability is:
http://maps.google.com/maps?hl=en&ie=UTF8&ll= + latitude + , + longitude + &spn=0.054166,0.110378&z=13&output=embed
The latitude and longitude variables contain coordinate values. So, the trick is to locate the latitude and longitude values to insert where theyre needed.
To filter out browsers that do not recognize the geolocation object, use a simple trap:
if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(someFunction); } else { alert(Geolocation not recognized) }
This tells users whether their browsers even recognize geolocation. The function called to get the position information makes the call but is expected to include a parameter that will store the actual information about location. Following the practice of using objects and methods the call is made:
... navigator.geolocation.getCurrentPosition(LocationMaster.lookUpPosition); ...
This, in turn, gets the method that returns the requested values:
Note that the position parameter is like a variable that will store the latitude and longitude values. It is not a property of the geolocation object cords.latitude and cords. longitude are the properties. (The name position could be any name we wanted Rumpelstiltskin wouldve worked, but position is more descriptive.) Once the values are assigned to the parameter object, they become part of the LocationMaster object using the this keyword. The property names latNow and longNow store the values like a variable. The only difference is that theyre part of an object.
307
You find a new method in the HTML5 DOM core: getElementById. In this case, the ID is that of an iFrame element. Then the map is the source object just like an image is loaded through the source identification:
<img src=myImage.jpg>
The only difference is that the place where the map is loaded is specified by the iFrame ID instead of by the page by default.
308
When you test this Web page, try it first using the latest Firefox browser. Then try it out with Google Chrome and Opera. With Safari, which recognizes the geolocation object, I was unable to load the map into the iframe. Ironically, when tested on the mobile Safari browser on an iPhone, it worked fine. (More about that in a second.) Figure 15-1 shows the program on all browsers except Safari and Internet Explorer running on Windows 7.
309
Figure 15-1: Geolocation used to nd longitude and latitude for Google Maps.
Figure 15-1 shows the Web page loaded with the map in Firefox, Chrome, and Opera. You can drag the map around the iframe with the mouse and on Safari and Perfect browsers on an iPhone, with your fingers. However, on the mobile browsers, the iframe and image were extended by dragging downward.
Now on a vertical orientation, the map was easier to read. Figure 15-2 shows the program on an iPhone in the Perfect (left) and Safari (right) browsers. Near the bottom of the page, directions provide mobile users with instructions for enlarging the image without dragging the map out of the iframe.
310
Figure 15-2 illustrates that by pulling the page outward and away from the map (left panel), mobile users can adjust the map so that they can easily read it (right panel).
WORKING WITH THE GEOLOCATION PROPERTIES AND THE GOOGLE EARTH PLUG-IN
Experimenting with the geolocation object can be a lot of fun and very informative. The following is a full list of its properties:
latitude: Geographic coordinates in decimal degrees longitude: Geographic coordinates in decimal degrees altitude: Height in meters accuracy: Accuracy levels of latitude and longitude coordinates in meters altitudeaccuracy: Accuracy levels of altitude in meters heading: Direction of travel of hosting device in degrees (most relevant to a mobile device) speed: Current ground speed of hosting device in meters/second (most relevant to a mobile device)
If you have a mobile device, you can experiment with different headings and speed with someone else driving! All the geolocation properties can be sent to a form for display if you want. If used with a mobile device, youll need either an open-socket server or frequent browser/page refreshing. A final aspect of geolocation is the use of the Google Earth plug-in. Figure 15-3 shows a revised version of the basic Web page with the plug-in that can generate a 3-D view of the mapped area. You can update the sample Web page to the same dimensions by giving the <iframe> tag the following attributes: width=500 height=400. Then click the Earth option at the top of the map area. If your browser has the plug-in, it will show the 3-D view. Otherwise, itll offer you a chance to download the plug-in and install it on your browser.
311
STORAGE IN HTML5
Other than cookies that store data on the users browser, when you think about storage, typically a database and other programs like PHP and ASP.NET come to mind. However, the HTML5 DOM now has a storage object that can be used in four contexts:
Not all browsers support all these storage contexts, but as browsers are continuously updated to include HTML5, they include more contexts. At the time of this writing, Safari, Chrome, and Opera supported all the contexts except global storage; Firefox supported them all except database storage.
312
Figure 15-3: A 3-D view of the map area with the Google Earth browser plug-in.
All storage is done in key/value pairs. The key is an identifier for a given value. (The key is something like a variable with a label and an assigned value.) The next two sections explain how to work with session and local storage. Global and database storage are less universally implemented at this time, so Im setting them aside.
SESSION STORAGE
Session storage allows users to store data for a single Web page as long as that Web page is being viewed. As soon as the user leaves the page, all stored data is lost. For interactive games, calculators, and any other kind of page that needs temporary storage while the page is viewed, you can use session storage. To get started, youll need to take look at the setters and getters of session storage. Heres the basic format for setting (storing) a value:
The key must be a string, while the value can be any acceptable data type number, text, Boolean, object, function. The following represent some valid data assignments:
this.myKey=secondKey; //Key name assigned to property function eek() { return eeeek!; } jill=My name is Jill; //A variable //Assign values to keys sessionStorage.setItem(firstKey,88); sessionStorage.setItem(this.myKey,true ); //A number (numeric literal) //Boolean //A function with a return value
As you can see, you can use variables for both keys and their values. As long as the variable (or property) is a string, it can be used as a key you could even use a function that returns a string as a key. A value can be a string or nonstring. Once you have stored data, you need a way to retrieve it with a getter method. The following shows the general format for getting the stored data you have to know the key name for every value you want to retrieve.
sessionStorage.getItem(keyName);
313
You can think of the key name in the same way as you do a variable name. If you know the variable name, you can find its value. Key names work the same way. This next program (SessionStore.html in this chapters folder at www.wiley.com/ go/smashinghtml5) provides a simple illustration of how to work with session storage. Youll probably be reminded of working with variables because the values are extant only as long as you dont change the page.
<!DOCTYPE HTML> <html> <head> <script type=text/javascript> StorageMaster=new Object(); //Set values StorageMaster.setPositions=function() { sessionStorage.setItem(firstBase,document.players.firstBase.value ); sessionStorage.setItem(secondBase,document.players.secondBase.value ); sessionStorage.setItem(thirdBase,document.players.thirdBase.value ); } //Get values
314
315
When you first load the page, youll see a new HTML5 attribute in all the text input windows these are place holders. In the code, they look like this:
<input type=text name=thirdBase placeholder=Third base>
As soon as the user begins to type in a value, they immediately disappear. So, go ahead and test it, filling in the three text windows, and then click the Assign Positions button. That sets the values in the session storage. To retrieve the stored data, just click any of the three buttons in the Whos Playing What? box. Figure 15-4 shows what you can expect to see. If you try to get the stored data back before clicking the Assign Positions button, youll get a null value in the alert window. If you leave the page and return, youll also get null values until youre reassigned the positions.
316
LOCAL STORAGE
The main difference between session storage and local storage is that local storage is persistent. Users can leave the site, turn off their computers, come back the next day, and the data are still there. Local storage works very much like cookies, but there are certain differences that are important:
Cookies allow very little storage space; local storage allows far more. Cookies are retransmitted automatically with every request to the server, and local storage is not which means local storage is far less work for the server and browser. Local storage is transmitted on a request only.
Youll find that localStorage and sessionStorage use the same getter/setter methods, so once you know one, you know the other. However, you can set a value using localStorage, turn off your computer, go play a game of football, come home, turn on the computer, and your data is still stored on your computer. The following example (LocalStorage.html in this chapters folder at www.wiley.com/go/smashinghtml5) shows how to store, retrieve, and clear localStorage data.
<!DOCTYPE HTML> <html> <head> <script type=text/javascript>
317
318
One of the features added to this example is the use of radio buttons to pass data to be stored. Radio buttons are important because they make it easy for users to make a choice. It does take a bit more work to get the correct data from radio buttons and check boxes, but it reflects the Web truism that the more work the developer does, the less work users have to do. Another feature of local storage is that its related to the browser. Each browser has its own storage. So, if you store the data using a Safari browser, a Chrome browser cannot access that data. Figure 15-5 shows the page loaded in a Chrome browser that has stored data using local storage. However, if the same program in a different browser (Opera, for example) attempts to retrieve the data, it shows it to be null.
319
You may also notice that when you first load the program, you dont see the output window. Instead, you see a gray line beneath the buttons. As soon as you click the Find Info button, the information appears where the gray line was. A little CSS3 and HTML5 DOM work does the trick. First, in the CSS3, set up the ID:
the information stored in this.profile was sent to the Web page where the following tag was placed:
<pre id=profile></pre>
Prior to HTML5, dynamically sending data to a Web page without reloading the page was far more complex. However, for certain programs like Adobe Flash CS5, its quite easy, as the next section explains.
320
ADDING AN OBJECT
To give you an idea of how to embed an object in HTML5, I created a simple animation of a shooting star in Flash CS5. Figure 15-6 shows the little animation in the design window.
You can place the animation into a Web page in a number of different ways, but the easiest is to publish it in Flash, which automatically generates a Web page with a reference to the binary file in a .swf format. In browsers with Flash plug-ins, which is virtually all browsers they ship (or download) with the Flash plug-in included the following code (ShootingStar. html in this chapters folder at www.wiley.com/go/smashinghtml5) shows the object in an HTML5 wrapper.
<!DOCTYPE HTML> <html> <head> <title>ShootingStar</title> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <style type=text/css media=screen> html, body { height:100%; background-color: #ffffff;} body { margin:0; padding:0; overflow:hidden; } #flashContent { width:100%; height:100%; } </style> </head> <body> <div id=flashContent> <object classid=clsid:d27cdb6e-ae6d-11cf-96b8-444553540000 width=300 height=200 id=ShootingStar align=middle> <param name=movie value=ShootingStar.swf /> <param name=quality value=high /> <param name=bgcolor value=#ffffff /> <param name=play value=true /> <param name=loop value=true /> <param name=wmode value=window /> <param name=scale value=showall /> <param name=menu value=true /> <param name=devicefont value=false /> <param name=salign value= /> <param name=allowScriptAccess value=sameDomain /> <!--[if !IE]>--> <object type=application/x-shockwave-flash data=ShootingStar.
321
322
ADJUSTING AN OBJECT
The key HTML5 element is the <object> tag. Several parameters have been included, but all of them can be changed to better suit your site. For example, the background color is set to white (#ffffff), and by typing in a different background color, you can match it to your site. Likewise, you can change the CSS and anything else you want. Another program variously called Flex and Flash Builder also generates .swf files. Using a very powerful language called ActionScript 3.0, developers are able to create programs with the same depth and power as established programs like Java and C++. However, all the HTML5 developer has to do is add the .swf file with his own code or code generated automatically by Flash and Flash Builder.
Get the longitude and latitude for five different locations. Enter the longitude and latitude values into a localStorage object. Set up five buttons that will call a JavaScript program that will load five maps when requested.
Basically, youll be making a Web page that loads maps of anyplace you choose. You shouldnt need any more JavaScript than the little that has been covered in this chapter.
323
SMASHING HTML5
16
ONE OF THE most powerful and practical aspects of working with Web programming is the ability to store and retrieve data. HTML5 has some capacity for such data storage and retrieval; however, as Chapter 15 showed, any data that is stored is going to be related to an individuals browser. As you saw in Chapter 15, for the time-being, all the browsers arent exactly playing nicely together in the sandbox when it comes to data storage. Plus, the data are stored on the users computer, and while thats useful for some things, such as recognizing a users interests when returning to a Web site, every user has some kind of local storage. How do you store data (like a blog comment) so that anyone with a browser can access it? To give you a sense of what this chapter introduces, consider something simple you can do on the Web: maintain and comment on a blog. Suppose you have a blog that discusses HTML5. Once or twice a week, you sit down and write a blog entry about HTML5. Now suppose you attract a big audience of blog readers, and these readers comment on your entries. How do you store and retrieve your
CHAPTER 16
326
Returns HTML5
Server-side processing Client Requests PHP Page Returns HTML5 Server Storage
In Figure 16-1, the real work is between storage and the server. The information in storage has to be configured in a way that it can be read by your browser. And thats what PHP does it takes the stored information (sent in as a blog entry, for example) and sends it back as HTML5.
Sign up for a hosting service. Download and install a server and PHP on your computer. If you have Mac OS X, its already on your computer just configure it.
Windows only: Go to http://windows.php.net/download and download the latest stable version of PHP5. (Youll find What version do I choose? in the left column to help you choose what you need for your system.) Youll also need to install an Apache server; you can get one free from www.apache.org. Macintosh only: Go to http://foundationphp.com/tutorials/php_ leopard.php and follow the instructions for accessing the PHP on your system. (Be very careful because youre going to be using the built-in Terminal in your Mac and youll be changing some key files.) This Web site shows you how to set up both PHP and your built-in Apache server. The easiest method for all users: If you want to download and install everything at once (PHP, Apache server, and a MySQL database) for your Mac go to www.mamp.info/en/ index.html and for Windows go to www.wampserver.com/en. This is the easiest way to set up an actual database on your computer. 327
Setting up PHP and Apache can be awkward, but once its set up, you dont have to do it again. If you use the all-in-one method (the last one listed above), you can get the MySQL server with which you can set up a database on your computer.
TESTING PHP
Once you have your system set up, whether its on your computer or a hosting service, enter the following program and test it:
<!DOCTYPE HTML> <html> <head> <?php print phpinfo(); ?> <meta http-equiv=Content-Type content=text/html; charset=UTF-8> <title>Test PHP</title> </head> <body> </body </html>
Save the program as First.php and place the file in your Apache root folder. For example, the following path is a typical one for Windows: c:/Program File/apache Groub/ apache/htdocs/php. The added folder, php, is where to put your First.php. On a Mac,
328
Your installed version may be different, but that information tells you that PHP is installed on your system and ready to go.
PHP BASICS
Before getting to something practical, the first few steps describe some basic syntaxes and operations of PHP. PHP has many unique features, but its very much like JavaScript with a slightly different set of symbols. The most important fundamentals begin with PHP catching data sent from the client. In order to emphasize the difference between client-side and server-side operations, the PHP code will be divorced from an HTML5 wrapper.
329
The script includes both a text type and email type input form. (If no type of form is assigned, it defaults to a text type.) An important detail to note is that the Submit button is given a name (sender) that is used by the PHP script to determined whether the data from this form has been sent.
PART IV:DYNAMIC HTML5 TAGS PLUS A LITTLE JAVASCRIPT AND PHP THE POST CATCHER
On the PHP side that catches the data, the $_POST array expects the name of the form. Two variables are first declared $name and $email. Variables in PHP have a dollar-sign ($) prefix. However, before the PHP program attempts to assign the variable with data from the $_POST array, a good practice is to check the isset() function that checks to see if the Submit button (named sender) has sent the data. (The following code is in formCatcher. php in this chapters folder at www.wiley.com/go/smashinghtml5.)
<?php //Catch HTML5 Data $name; $email; if(isset($_POST[sender])) { $name=$_POST[formName]; $email=$_POST[formEmail]; } print $names email address is $email; ?>
330
Formatting the output using the print statement combines the variables and text in a single set of double quotes. Within quotation marks, PHP still recognizes variables because the dollar sign ($) prefix tells the interpreter that, even within quotes, the word is a variable. Most other languages require concatenation when joining variables and literals. Figure 16-3 shows both the form as filled and the output generated by PHP. (Note the localhost address in the URL window for both the top and bottom panels.) Thats a simple program, but it does show how PHP passes data from HTML5 to PHP. Youll also find a very interesting result in the e-mail window when you type in something thats not in e-mail format. Youll find that it isnt passed to the PHP module. Instead, it uses the new HTML5 structure the e-mail input format and it acts like a data input validator that doesnt tell the user that shes messed up.
DATA VALIDATION
In order to help users, the HTML5 portion of the application uses an error catcher routine and informs users that theyve made an error in the two parts of the Web page. First, the e-mail form includes an error handler:
<input type=email size=32 NAME=formEmail placeholder=Enter Name onInvalid=SendMaster.eLert()>
331
Second, the JavaScript routine in the <head> of the page triggers an alert message:
SendMaster=new Object(); SendMaster.eLert=function() { alert(Oops! Seems to be a little boo-boo in the e-mail format.); }
You might want to note two important features about the coding:
It uses onInvalid instead of onError. The onError event handler is so commonly used for any kind of error that you might assume it would work here as well, but only onInvalid works in this case. The error-catching routine is in the <input> e-mail instead of the <input> submit tag. Because the error occurs on clicking the Submit button, it would seem that the error handling would be in the Submit button tag, but its not. Figure 16-4 shows the error message and the error that caused it note the hand cursor on the sent (Submit) button.
The value attribute of the Submit button should be named anything but Submit as a good interactive design practice. Thats why its value is set to Send. (No wants to submit.) Also, the message isnt one of those hysterical gasps like FATAL ERROR! E-mail format illegal! Some users find such messages disconcerting. Also, theyre inaccurate no one died or was arrested. It was just a boo-boo. 332
That means you only can assign string data types to the variable, username. If you assign it a number, Boolean, or nonstring function, it throws an error. PHP is like JavaScript. If you assign the PHP variable,
$userName =SoSueMe;
Weakly typed languages have certain advantages and disadvantages, but they tend to be easier to learn initially.
Variables
As mentioned earlier in this chapter, all variable labels begin with a dollar sign ($). They can be placed in other strings and recognized regardless of data type. Try out the following (variableInString.php in this chapters folder at www.wiley.com/go/ smashinghtml5):
<?php $ram = dynamic random access memory; $speed =much GHz in; $money= 2; $truism =You cant have too much $ram or too $speed a processor. (That will be $money cents for the advice.); print $truism; ?>
333
When you test that code, youll see the following output:
You cant have too much dynamic random access memory or too much GHz in a processor. (That will be 2 cents for the advice.)
Constants
Constants are like variables in PHP except they do not change in value. Theyre assigned values in a much different way than variables are, and theyre case-sensitive. By convention (and good practice), theyre in all caps (LIKE_THIS). The basic assignment format is:
define(CONSTANT_NAME, value);
Try the following little script (constants.php in this chapters folder at www.wiley. com/go/smashinghtml5), to get an idea of how they work:
<?php define(FRED, Fred J. Jones ); define(MONEY, 200); define(BUCKS, $); echo FRED , donated , BUCKS , MONEY , to charity.; ?>
As you can see by putting the dollar sign character ($) into a constant, you can use it with financial expressions and it wont be mistaken for a variable. By the way, you can use either echo or print (as well as other statements) in PHP to send output to the screen.
Arrays
An array is an object that holds several values. Its like a container on a container ship where different objects are stored dolls from China, car parts from Detroit, computers from Japan, and corn from Iowa. They work just as arrays do in JavaScript, but theyre configured a bit differently. (See Chapter 12 for more on arrays.) Arrays are named like variables except theyre assigned array objects. For setting up an array, you can use one of two basic formats. The preferred format works like an associative array. Instead of identifying an array element with a number, its given a key with a value a key-value pair. Heres the general format for setting up an associative array:
$associate = array(key1 => value1,key2 => value2);
334
The other kind of array has a numeric key. Most typically, its set up by listing the array elements in the following format:
$numeric=array(el0,el1,el2,3, true);
The following little script (array.php in this chapters folder at www.wiley.com/go/ smashinghtml5), shows several different combinations you can see:
<?php $associate = array(key1 => value1,key2 => value2,keyEtc => valueEtc); $boxCar=array(tools,oil drum,cow,7, false, computer parts); $mixedBag=array(1=>first,2=>second,third=>3,4=>4); echo $associate[key2] . <br>; echo $associate[keyEtc] . <br>; echo $boxCar[5] . <br>; echo $boxCar[0] . <br>; echo $mixedBag[2],$mixedBag[third]; ?>
Arrays are important in PHP because database data are often loaded into an array for output.
335
Youll find other differences, but the similarities are far more numerous between PHP and JavaScript.
Assignment
336 To assign a value to a variable or object, the equal sign (=) serves as the assignment operator. Compound PHP operators assign the value of the current variable plus, minus, multiplied by, or divided by the assigned value. The following example (assignment.php in this chapters folder at www.wiley.com/go/smashinghtml5), shows the key uses of assignment operators:
<?php $sampleNum=20; $sampleString=Hurricane; $sampleNum += 50; $sampleString .= is coming.; echo $sampleNum,<br>; $sampleNum *= 2; echo $sampleNum,<br>; $sampleNum /= 4; echo $sampleNum,<br>; echo $sampleString; ?>
Before you look at the outcome, see if you can predict what theyll be:
70 140 35 Hurricane is coming.
Arithmetic
The arithmetic operators are fairly standard compared to other programming languages. The main ones include
About the only one that anyone has problems with is modulo (%). It refers to any remainders of whole numbers after division. However, they can be handy. For example, the following little program (modulo.php in this chapters folder at www.wiley.com/go/smashinghtml5), demonstrates how it can be used with a Boolean:
<?php for ($count = 1; $count <= 12; $count++) { $valid = $count % 2; if($valid) { echo $count, is odd<br>; } else { echo $count, is even<br>; } } ?>
337
The program iterates through a series of numbers divided by 2. Even numbers divided by 2 return 0 and odd numbers return 1 the values Booleans recognize as false and true, respectively. The if() statement is looking for a true or false and will accept ones and zeros as Booleans. When sending out alternating backgrounds in table data coming from a database, the modulo operator is used to switch colors back and forth using the trick of dividing record numbers by 2 and using the remainder (modulo) as a Boolean.
338
{ alert(Hmmmm... It seems that the e-mail entry has something out of sort. . . . Please take a look at it and see if you can fix it up.) } </script> <style type=text/css> /*DDDCC5,958976,611427,1D2326,6A6A61 */ body { background-color:#DDDCC5; color:#1D2326; font-family:Verdana, Geneva, sans-serif; } h2 { background-color:#958976; color:#DDDCC5; text-align:center; font-family:Arial Black, Verdana, Arial; } h3 { color:#611427; } fieldset { color:#6A6A61; } </style>
339
One of the key lines in the HTML5 script is the action in the form that sends the information to PHP for processing:
<form action=mailer1.php method=post>
The form was not given a name because, for this application, we didnt need one. However, adding a name to the form is generally a good practice, and if its needed, it should be available. All the name attributes in the input elements are crucial. Each name in the input element tags is passed to PHP as an array element in the $_POST array. The element is then passed to a variable that is used in the e-mail that is sent to a recipient typically, the Web site owner. In this case, thats you. Figure 16-5 shows the input page and the form data that will be sent to the PHP program for server-side processing. As soon as the user clicks the Send E-Mail button, he receives a notice:
Your e-mail has been sent to [email protected]. Thank you for your interest in Wazoo Web Site Design and Development.
To see how that happened, well have to look at the PHP portion of the application.
340
In looking at the PHP code, you can see it doesnt take much. First, the four chunks of data from the HTML5 page are passed to four PHP variables:
Next, the $comments variable is concatenated with information about the senders name and e-mail address. Then, using the mail() function, the program uses the following line to send everything to the Web site owner:
mail($eBiz,$subject,$comments);
Finally, a simple message is sent to the user who sent the e-mail. Figure 16-6 shows the e-mail received by Wazoo Web Site Design and Development.
341
By having an automatic e-mail page on your site, you (or your clients) can generate far more business. The key to using some kind of Web-generated e-mail is to make it easy for the user to send an e-mail and generate more business for the site.
PART IV:DYNAMIC HTML5 TAGS PLUS A LITTLE JAVASCRIPT AND PHP ADDING A HEADER AND AUTO-REPLY IN PHP
As was hinted in the fictitious e-mail used in the example, it would be nice to have an automatic e-mail reply to users when they send an e-mail. Again, using the mail() function in PHP, all you have to do is add a second mailer. Using the $name variable and $email, you can personalize a reply. Additionally, you can add a header to the e-mail that is sent to the user and to the Web site owner. First, the mail() function requires a fourth parameter. Breaking down the four parameters, you can lay out the following:
Recipient (e-mail address) Subject (what is placed in the subject line) Content (the body of the message) Header (the From and Reply To addresses)
In the initial example, the From and Reply To address was concatenated to the content. However, using the header parameter, you can let the header take care of it. This next listing (mailer2.php in this chapters folder at www.wiley.com/go/ smashinghtml5), shows the same program with the added header and the auto-reply. Very little has been added, and much has been enhanced. 342
<?php $name; $email; $comments; $subject; [email protected]; if(isset($_POST[sender])) { $name=$_POST[userName]; $email=$_POST[mailNow]; $comments=$_POST[talk]; $subject=$_POST[subject]; } $headers = From-> $name :\r\n Send reply to: $email; $reply=Dear $name , \r\n Thank you for sending us your comments. We at Wazoo Web Site Design and Development believe that customer care is an essential of doing businessnot an optional service.\r\n; $reply .= As soon as we can review your comments, one of our associates will get back to you.; $reply .=\r\n Sincerely, Phillip Pickle,\r\n President, WWDD; mail($email,Thank you for your thoughts,$reply); mail($eBiz,$subject,$comments,$headers); echo Your e-mail has been sent to $eBiz. Thank you for your interest in Wazoo Web Site Design and Development.; ?>
The user sees that his name is in the header, and the subject line is based on what the user just sent. Even though the user probably realizes that its an auto-generated reply, he likes the fact that a Web development company can do that for his business. The addition of the header makes it easier to add a header where you want it. In the first example, the header was really a footer at the end of the message. This time, its where it belongs at the top of the e-mail, as shown in Figure 16-8.
343
Four radio buttons requesting information about users type of business Four check boxes requesting information about the services the user was interested in using
That may not look like much of a challenge, but if you can make data entry easy for users and access that information in PHP, then you have some very powerful tools at your beck and call.
344
Index
SYMBOLS AND NUMERICS
+ (addition operator), 337 <> (arrow brackets), 89 / (division operator), 337 . (dot), 60 (double quotes), 34, 35 % (modulo operator), 337 * (multiplication operator), 337 # (pound sign), 62 ; (semicolon), 40 (subtraction and negation operator), 337 | (vertical bar), 40 3GP video format, 217, 221222 objects in Web pages, 320 style to text with CSS3 embedded style sheets, 5354 external style sheets, 5558 inline style, 5859 styling HTML5 elements with CSS3 properties, 5253 styles to drawings, 262264 transparency to color, 7476 addition (+) operator, 337 adjusting GIF file size, 185186 image file size with graphic applications, 182 JPEG file size, 183185 objects in Web pages, 321 PNG file size, 185186 SVG file size, 186187 Web pages for mobile viewing, 310 Adobe Browserlab, 20 Adobe Dreamweaver CS5, 20 Adobe Illustrator, 194196 Adobe Media Encoder CS5, 221222 alert() function, 235 alert windows, displaying choices in, 295296 align attribute, 189191 alternate style sheets, 128131 anchors (page), 137140 Apple iSight webcams, 223 QuickTime Player, 225 Apple Safari. see also video support for audio, 203 using to interpret HTML5, 2223 applying CSS3 pseudo-classes, 160162 Arabic language attribute value, 34 arcs, drawing, 276279 arithmetic operators, 337 arrays overview, 248249 PHP, 334335 $_POST, 330 arrow brackets (<>), 89 assigning colors using percentages, 6769 icons to rel attribute, 131132 values to preload attribute, 202203 assignment operators, 336337 attributes accept-charset, 286287 action, 287 align, 189191 autocomplete, 288 autoplay, 200, 228 colspan, 120122 controls, 228229 defined, 33 enctype, 286287 height, 229 href, 133 hreflang, 133 lang, 3435 link, 133 list, 294 loop, 227228 media, 133 name, 288290 novalidate, 286287 poster, 226227 preload, 202203, 227
A
<a> tag links. see links absolute reference, 104 accept-charset attribute, 286287 action attribute, 287 adding auto-replies in PHP, 342344 borders to tables with CSS3, 114117 drop shadows, 265267 forms accept-charset attribute, 286287 action attribute, 287 autocomplete, 288 DOM, 290292 name attribute, 288290 overview, 284285 headers in PHP, 342344 HTML5 structure, 4952 metadata to Web pages, 8788
INDEX
attributes (continued)
rel
bit, 72
<body> tag, 3233, 86
C
Cabarga, Leslie (author) Designers Guide to Color Combinations, The, 78 camcorders, 223224 Camtasia software, 225 <canvas> tag adding styles, 262264 creating drawings arcs, 276279 circles, 279281 curves, 275276 gradients, 279281 lines, 270275 movement, 270275 overview, 258260, 269270 grid, 256257 images adding drop shadows, 265267 filters, 267269 loading, 264265 implementation, 256 overview, 253256 practice examples, 281 removing drawings, 262264 scripts, 8990 setting up drawings, 257258 transparency, 74 working with multiple drawings, 260262 <caption> tag, 113114 captions, organizing, 100103 Cartesian coordinates, 256257 cells (table), 120 <center> tag, 1617 changing GIF file size, 185186 image file size with graphic applications, 182 JPEG file size, 183185 objects in Web pages, 321 PNG file size, 185186 SVG file size, 186187 Web pages for mobile viewing, 310 check boxes, 297301 Chinese language attribute value, 34
346
assigning icons to, 131132 prefetching, 133 values for, 134 rowspan, 120122 sizes, 133 src, 44, 226 target, 140141, 290 title, 133 type, 133, 204205 width, 229 audio. see also video Apple Safari support, 203 autoplay attribute, 200 browser support for, 203204 controls, 200202 converting files, 208 creating files Macintosh OS X Sound Studio, 208209 overview, 206 Windows 7 Sound Recorder, 206207 loop, 203 overview, 199200 practice examples, 214 preload attribute, 202203 sound effects integrating into Web pages, 211213 overview, 209 transitions sounds, 209211 <source> tag, 204 <audio> tag. see audio author relations, 135137 autocomplete attribute, 288 autoplay attribute, 200, 228 auto-replies, adding in PHP, 342344
B
background colors, data clarification with, 117119 bandwidth, saving, 185 base color, creating color schemes from, 76 <base> tag, 8687
book, organization of, 23 Boolean, 245 borders, adding to tables with CSS3, 114117 <br> tag, 4546 Browserlab (Adobe), 20 browsers Apple Safari support for audio, 203 using to interpret HTML5, 2223 audio support, 203204 compatibility with video Adobe Media Encoder CS5, 221222 overview, 218219 WebM Miro Video Converter, 219220 displaying icons with, 132 Google Chrome browser audio controls, 201202 support for audio, 203 using to interpret HTML5, 1921 Microsoft Internet Explorer grayscale on, 188 support for audio, 203 using to interpret HTML5, 24 Mozilla Firefox support for audio, 203 using to interpret HTML5, 1819 Opera support for audio, 203 using to interpret HTML5, 2122 overview, 17 practice examples, 2526 previewing different displays, 2425 using style sheets with different, 130 browsing contexts in computer browsers, 141142 in mobile browsers, 142143 byte, 72
INDEX
choosing Apple Safari, 2223 Google Chrome, 1921 microphones in Windows 7 Sound Recorder, 206 Microsoft Internet Explorer, 24 Mozilla Firefox, 1819 Opera, 2122 overview, 17 Chrome (Google) browser audio controls, 201202 support for audio, 203 using to interpret HTML5, 1921 circles, drawing, 279281 classes (CSS3), 5961 code, parsing, 28 codec parameter, of type attribute, 205206 color background, data clarification with, 117119 Web safe, 177 color values adding transparency to color, 7476 creating color schemes, 7478 integrating color palettes with Web pages, 7881 practice examples, 81 RGB color hexadecimal settings, 7174 names, 6667 overview, 66 RGB and HSL percentages, 6769 RGB decimal integer settings, 7071 colspan attribute, 120122 <comment> tag role of, 3537 when to use, 38 compatibility (browser) Adobe Media Encoder CS5, 221222 overview, 218219 WebM Miro Video Converter, 219220 consistency (navigation) applying CSS3 pseudo-classes, 160162 HTML5 mechanics of vertical navigation, 162165 overview, 159160 using graphic icons in navigation, 165166 vertical and horizontal navigation, 160 constants (PHP), 333334 controls (audio), 200202 controls attribute, 228229 converting files, 208209 creating audio files Macintosh OS X Sound Studio, 208209 overview, 206 Windows 7 Sound Recorder, 206207 canvas drawings, 258260 color schemes, 7478 complex drawings with canvas arcs, 276279 circles, 279281 curves, 275276 gradients, 279281 lines, 270275 movement, 270275 overview, 269270 consistency in navigation applying CSS3 pseudoclasses, 160162 HTML5 mechanics of vertical navigation, 162165 overview, 159160 using graphic icons in navigation, 165166 vertical and horizontal navigation, 160 CSS3 classes, 5961 CSS3 IDs, 6263 HTML5 with tags, 89 objects, 250251 transition sounds, 209211 Web pages, 216218, 307309 CSS3 adding borders to tables with, 114117 adding style to text with embedded style sheets, 5354 external style sheets, 5558 inline style, 5859 styling HTML5 elements with CSS3 properties, 5253 applying pseudo-classes, 160162 creating classes, 5961 IDs, 6263 relationship with HTML5, 31 table properties for HTML5, 110112 curves, drawing, 275276
D
data clarification with background colors, 117119 types of, 245246 validation in PHP, 330332 data (interactive) e-mail applications adding headers and autoreply, 342344 creating, 337340 PHP catch and send, 340341 overview, 325 PHP data validation, 330332 overview, 328330 $_POST array, 330 PHP program structures arrays, 334335 constants, 333334 objects, 335336 operators, 336337 properties, 335336 temporary data storage, 332333 variables, 333 practice examples, 344
347
INDEX
data (interactive) (continued) server-side languages overview, 326 setting up PHP, 326327 testing PHP, 327328 <datalist> element on mobile devices and URL keyboards, 296297 overview, 9 datalists, 294 date picker, 301302 decimal integer settings (RGB), 7071 density (pixel), 58 designer navigation, 148149 Designers Guide to Color Combinations, The (Cabarga), 78 designing in sections, 9194 Designing Interfaces (Tidwell), 148 detecting events, 236237 discontinued tags, 1517 displaying choices in alert windows, 295296 icons with browsers, 132 displays, previewing, 2425 <div> tag, 9498 division (/) operator, 337 divisions, organizing, 9498 document type declaration, 44 DOM (Document Object Model) browser effects, 251252 form as part of, 290292 how it works with JavaScript, 240242 HTML5 elements with, 242244 overview, 239240 relationship with sections, 94 dot (.), 60 double quotes (), 34, 35 downloading sound effects, 211 drawings (canvas) adding styles to, 262264 creating arcs, 276279 circles, 279281 curves, 275276 gradients, 279281 lines, 270275 movement, 270275 overview, 258260, 269270 removing, 262264 setting up for, 257258 working with multiple, 260262 Dreamweaver CS5 (Adobe), 20 drop shadows, 265267 drop-down menus, in global navigation, 153156 dynamic SVG files, 194196 finding, 181 grayscale on Internet Explorer, 188 overview, 179181 files audio, creating Macintosh OS X Sound Studio, 208209 overview, 206 Windows 7 Sound Recorder, 206207 converting, 208209 external, 234235 fixing Windows default extension settings, 29 HTML5 and related, 28 organizing absolute reference, 104 image reorganization and reference, 103104 relative reference, 104106 for Web, 31 filters, 267269 finding file size, 181 latitude, 306307 longitude, 306307 Firefox (Mozilla) support for audio, 203 using to interpret HTML5, 1819 fixing TextEdit on Macintosh, 30 Windows default file extension settings, 29 FlashKit, 209 Flip Mino HD camcorder, 224 footer elements, 94 <form> tag, 242244 formats (image), 176 formatting grouping, 99100 forms adding accept-charset attribute, 286287 action attribute, 287 autocomplete, 288 DOM, 290292 enctype attribute, 286287 name attribute, 288290
E
elements span, 54
datalist, 9, 296297
348
defined, 33 DOM references, 242244 footer, 94 handling, 237239 iframe, 143146 link, 128 new HTML5, 911 styling with CSS3 properties, 5253 tables, 113 e-mail applications adding headers and autoreplies, 342344 overview, 337340 PHP catch and send, 340341 embedded style sheets, 5354 Emerson, Ralph Waldo (author) Self-Reliance, 159 enctype attribute, 286287 event handlers, 236 events, detecting, 236237 external files, JavaScript in, 234235 external style sheets, 5557
F
<figcaption> tag, 100103 <figure> tag, 100103
figures, organizing, 100103 file size changing with graphic applications, 182 JPEG, 183185 SVG size, 186187
INDEX
novalidate attribute,
286287 overview, 284285 attributes, 286292 input types check boxes, 297301 datalists, 294, 296297 date picker, 301302 displaying choices in alert windows, 295296 list attribute, 294 overview, 293294 radio buttons, 297301 URL type, 294 overview, 283 practice examples, 303 functions, 235, 245
graphics, linking to, 166167 Graphics Information Format (GIF), 177, 185186 grayscale on Internet Explorer, 188 grid, 256257 grouping without formatting, 99100
H
H.264 video format, 217 handling elements, 237239 <head> tag, 32, 86 headers, adding in PHP, 342344 Hebrew language attribute value, 34 Hedengren, Thord Daniel (author) Smashing WordPress: Beyond the Blog, 325 height attribute, 229 hexadecimal settings, 7174 <hgroup> tag, 5052 hierarchical link types, 137 Hindi language attribute value, 34 horizontal navigation, 160 <hr> tag, 99100 href attribute, 133 hreflang attribute, 133 HSL and RGB percentages, 6769 HTML (HyperText Markup Language), history of, 1 <html> tag, 86 HTML4, using continued tags from, 1115 HTML5 adding structure, 4952 choosing browsers to interpret Apple Safari, 2223 Google Chrome, 1921 Microsoft Internet Explorer, 24 Mozilla Firefox, 1819 Opera, 2122 overview, 17 previewing displays, 2425 creating with tags, 89 discontinued tags, 1517 elements, 911 nesting tags, 3840 overview, 7, 27
parsing code fixing TextEdit on Macintosh, 30 fixing Windows default file extension settings, 29 how files work with Web, 31 HTML5 and related files, 28 overview, 28 practice examples, 4041 styling elements with CSS3 properties, 5253 using tags from HTML4, 1115 hue-saturation-light (HSL) model, 6769 HyperText Markup Language. see HTML (HyperText Markup Language); HTML5
G
geolocation adapting pages for mobile viewing, 310 finding latitude and longitude, 306307 getting maps, 307 Google Earth plug-in, 310311 overview, 306 placing maps on Web pages, 307 practice examples, 321322 properties, 310311 putting pages together, 307309 geolocation object. see geolocation German language attribute value, 34 GIF (Graphics Information Format), 177, 185186 global navigation drop-down menus, 153156 overview, 149150 using lists in, 150153 Google Chrome browser audio controls, 201202 support for audio, 203 using to interpret HTML5, 1921 Google Earth plug-in, 310311 gradients, drawing, 279281 graphic applications, modifying image file size with, 182 graphic icons, using in navigation, 165166
I
icons displaying with browsers, 132 graphic, 165166 link, 131132 thumbnail, 167169 identifying parts of tags, 3334 IDs CSS3, 6263 page, 137140 iframe element, 143146 iframes practice examples, 171 single-page Web sites with linking to graphics, 166167 on mobile devices, 169170 overview, 166 thumbnail icons, 167169 Illustrator (Adobe), 194196 images application for dynamic SVG files from Adobe Illustrator CS5 files, 194196 in canvas and shadows adding drop shadows, 265267 filters, 267269 loading images, 264265 creating color schemes from, 7677
349
INDEX
images (continued) file size bandwidth, 185 changing GIF size, 185186 changing JPEG size, 183185 changing PNG size, 185186 changing SVG sizes, 186187 grayscale on Internet Explorer, 188 modifying, 182 file sizes, 179181 flexible size with JavaScript, 191194 formats, 176 GIF (Graphic Information Format), 177 JPEG (Joint Photographic Experts Group), 177 overview, 175, 176 pixels, 176 placing with the align attribute, 189191 PNG (Portable Network Graphics), 177178 practice examples, 196197 preserving layers in Web graphics, 178179 reorganizing and referencing, 10304 SVG (Scalable Vector Graphics), 176177 <img> tag, 44 information design, 148 inline frames nesting Web pages, 144146 overview, 143144 inline style, 5859 input types (forms) check boxes, 297301 datalists, 294, 296297 date picker, 301302 displaying choices in alert windows, 295296 list attribute, 294 overview, 293294 radio buttons, 297301 URL type, 294 inserting JavaScript into Web pages detecting events, 236237 event handlers, 236 external files, 234235 functions, 235 handling with elements, 237239 overview, 234 integrating sound effects into Web pages, 211213 interactive data e-mail applications adding headers and autoreply, 342344 creating, 337340 PHP catch and send, 340341 overview, 325 PHP data validation, 330332 overview, 328330 $_POST array, 330 PHP program structures arrays, 334335 constants, 333334 objects, 335336 operators, 336337 properties, 335336 temporary data storage, 332333 variables, 333 practice examples, 344 server-side languages overview, 326 setting up PHP, 326327 testing PHP, 327328 interface design, 148 Internet Explorer (Microsoft) grayscale on, 188 support for audio, 203 using to interpret HTML5, 24 iSight webcams, 223 inserting in Web pages detecting events, 236237 event handlers, 236 external files, 234235 functions, 235 handling with elements, 237239 overview, 234 overview, 233 practice examples, 170171, 252 storing temporary values arrays, 248249 creating objects, 250251 DOM and browser objects, 251252 objects, 249250 overview, 244 types of data, 245246 variables, 244245, 246247 JPEG (Joint Photographic Experts Group), 177, 183185
K
Kodak Pocket Video camcorder, 224 Kuler, 76
350
L
lang attribute, 3435 languages (server-side) overview, 326 setting up PHP, 326327 testing PHP, 327328 latitude, finding, 306307 layers, preserving in Web graphics, 178179 lines, drawing, 270275 link element, 128 linking to graphics, 166167 links inline frames nesting Web pages, 144146 overview, 143144 link element and attributes alternate style sheets, 128131 link attributes, 133 link icons, 131132
J
Japanese language attribute value, 34 JavaScript calling linked pages with, 156158 DOM (Document Object Model) how it works, 240242 HTML5 elements, 242244 overview, 239240 flexibility of image size with, 191194
INDEX
overview, 128 prefetching, 133 overview, 127 page links author relations, 135137 browsing contexts in browsers, 141142 browsing contexts in mobile browsers, 142143 hierarchical and sequential links types, 137 overview, 134 page anchors and IDs, 137140 page IDs, 137140 rel attribute, 134 sequential links types, 137 targets, 140141 practice examples, 146 Linux, supported by Mozilla Firefox, 18 list attribute, 294 lists organizing, 9498 using in global navigation, 150153 loading images into canvas, 264265 local storage, 316320 longitude, finding, 306307 loop attribute, 227228 looping audio, 203 metadata, adding to Web pages, 8788 Microsoft Internet Explorer grayscale on, 188 support for audio, 203 using to interpret HTML5, 24 Microsoft Movie Maker, 223 Miro Video Converter, 219220 mobile browser, browsing contexts in, 142143 mobile devices adapting Web pages for, 310 datalist elements on, 296297 using iframes on, 169170 modifying GIF file size, 185186 image file size with graphic applications, 182 JPEG file size, 183185 objects in Web pages, 321 PNG file size, 185186 SVG file size, 186187 Web pages for mobile viewing, 310 modulo (%) operator, 337 MoMA (Museum of Modern Art), 148149 Mosaic. see Mozilla Firefox Movie Maker (Microsoft), 223 Mozilla Firefox support for audio, 203 using to interpret HTML5, 1819 multiplication (*) operator, 337 Museum of Modern Art (MoMA), 148149 Muybridge, Eadweard (film maker), 106107 overview, 159160 using graphic icons, 165166 vertical and horizontal navigation, 160 overview, 147 practice examples, 170171 single-page Web sites with iframes iframes on mobile devices, 169170 linking to graphics, 166167 overview, 166 thumbnail icons, 167169 using JavaScript to call linked pages, 156158 Web navigation concepts designer navigation, 148149 global navigation, 149156 overview, 148 user navigation, 148149 code, 40 negation () operator, 337 nesting tags, 3840 nesting Web pages, 144146 Netscape Navigator. see Mozilla Firefox novalidate attribute, 286287 number, 245
351
O
Object-Oriented Programming (OOP), 251 objects adding in Web pages, 320 adjusting in Web pages, 321 creating, 250251 defined, 245
geolocation
M
Mac OS X, finding file size in, 181 Macintosh fixing TextEdit on, 30 installing PHP, 327 Macintosh OS X Sound Studio, 208209 maps getting, 307 placing on Web pages, 307 media attribute, 133 Media Encoder CS5 (Adobe), 221222 menus (drop-down), in global navigation, 153156 <meta> tag, 44, 86, 8788
N
name attribute, 288290 names for colors, 6667 navigation strategies creating consistency applying CSS3 pseudoclasses, 160162 HTML5 mechanics of vertical navigation, 162165
adapting pages for mobile viewing, 310 finding latitude and longitude, 306307 getting maps, 307 Google Earth plug-in, 310311 overview, 306 placing maps on Web pages, 307 practice examples, 321322
INDEX
objects, geolocation (continued) properties, 310311 putting pages together, 307309 overview, 249250 PHP, 335336 OGG video format, 217 OOP (Object-Oriented Programming), 251 opacity, adding to color, 7476 Opera support for audio, 203 using to interpret HTML5, 2122 operators (PHP) arithmetic, 337 assignment, 336337 organizing captions, 100103 Web pages captions, 100103 designing in sections, 9194 divisions, 9498 figures, 100103 files, 103106 grouping without fracturing, 99100 lists, 9498 overview, 4547 paragraphs, 9498 practice examples, 106107 top of HTML5 document, 8690 <output> tag, 242244 page anchors, 137140
rel attribute, 134
352
P
<p> tag, 35, 9498 page anchors, 137140 page IDs, 137140 page links author relations, 135137 browsing contexts in computer browsers, 141142 browsing contexts in mobile browsers, 142143 hierarchical link types, 137 overview, 134
sequential link types, 137 targets, 140141 pages (Web) adapting for mobile viewing, 310 adding metadata to, 8788 objects, 320 adding style to text with CSS3 embedded style sheets, 5354 external style sheets, 5558 inline style, 5859 styling HTML5 elements with CSS3 properties, 5253 adjusting objects, 321 anchors, 137140 calling with JavaScript, 156158 creating CSS3 classes, 5961 CSS3 IDs, 6263 overview, 216218, 307309 describing with tags, 3233 fundamentals of, 4445 HTML5 structure, 4952 inserting JavaScript into detecting events, 236237 event handlers, 236 external files, 234235 functions, 235 handling with elements, 237239 overview, 234 integrating color palette with, 7881 integrating sound into, 211213 links author relations, 135137 browsing contexts in computer browsers, 141142 browsing contexts in mobile browsers, 142143 hierarchical sequential link types, 137 overview, 134 page anchors, 137140 rel attribute, 134 targets, 140141
nesting, 144146 organizing designing in sections, 9194 figures and captions, 100103 files, 103106 grouping without fracturing, 99100 overview, 4547 paragraphs, divisions, and lists, 9498 practice examples, 106107 top of HTML5 document, 8690 overview, 43 pixel density, 58 placing maps on, 307 structure of, 4749 palette (color), integrating with Web pages, 7881 paragraphs, organizing, 9498 parsing code, 28 Photo Booth application, 223 PHP adding auto-replies in, 342344 headers in, 342344 arrays, 334335 catch and send, 340341 constants, 333334 data validation, 330332 operators arithmetic, 337 assignment, 336337 overview, 328329 $_POST array, 330 program structures arrays, 334335 constants, 333334 objects, 335336 properties, 335336 temporary data storage, 332333 variables, 333 setting up, 326327 testing, 327328 pixels density of, 58 overview, 176
INDEX
pixels per inch (PPI), 58 placing images with align attribute, 189191 maps on Web pages, 307 plug-ins, 310311 PNG (Portable Network Graphics), 177178, 185186 Portuguese language attribute value, 34 $_POST array, 330 poster attribute, 226227 pound sign (#), 62 PPI (pixels per inch), 58 practice examples audio, 214 browsers, 2526 <canvas> tag, 281 color values, 81 forms, 303 geolocation, 321322 HTML tags, 4041 iframes, 170 images, 196197 interactive data, 344 JavaScript, 170171, 252 links, 146 navigation strategies, 170171 organizing Web pages, 106107 storage, 321322 tables, 125126 tags, 2526 video, 229230 Web design, 6364 prefetching, 133 preload attribute, 202203, 227 previewing different displays, 2425 properties geolocation, 310311 styling HTML5 elements with CSS3, 5253
R
radio buttons, 297301 reference absolute, 104 relative, 104106 refreshing tags, 88 rel attribute assigning icons to, 131132 prefetching, 133 values for, 134 relative reference, 104106 removing canvas drawings, 262264 RGB color hexadecimal settings, 7174 names, 6667 overview, 66 RGB and HSL percentages, 6769 RGB decimal integer settings, 7071 rowspan attribute, 120122 Russian language attribute value, 34
S
Safari (Apple). see also video support for audio, 203 using to interpret HTML5, 2223 saving bandwidth, 185 Scalable Vector Graphics (SVG), 175177, 186187, 194196 screen video capture, 225 <script> tag, 8990 scripts, reasons for using, 8990 sections, designing in, 9194 <select> tag, 153156 selecting Apple Safari, 2223 Google Chrome, 1921 microphones in Windows 7 Sound Recorder, 206 Microsoft Internet Explorer, 24 Mozilla Firefox, 1819 Opera, 2122 overview, 17 Self-Reliance (Emerson), 159 semicolon (;), 40
Q
QuickTime Player (Apple), 225
sequential link types, 137 server-side languages overview, 326 setting up PHP, 326327 testing PHP, 327328 session storage, 312316 setting up for canvas drawings, 257258 PHP, 326327 setting(s) file extension, 29 hexadecimal, 7174 home base on Web pages, 8687 RGB decimal integer, 7071 single-page Web sites with iframes linking to graphics, 166167 on mobile devices, 169170 overview, 166 thumbnail icons, 167169 size file changing JPEG, 183185 changing SVG size, 186187 finding, 181 grayscale on Internet Explorer, 188 modifying with graphic applications, 182 overview, 179181 image, 191194 sizes attribute, 133 Smashing WordPress: Beyond the Blog (Hedengren), 325 sound. see also video Apple Safari support, 203 autoplay attribute, 200 browser support for, 203204 controls, 200202 converting files, 208 creating files Macintosh OS X Sound Studio, 208209 overview, 206 Windows 7 Sound Recorder, 206207 loop, 203 overview, 199200 practice examples, 214 preload attribute, 202203
353
INDEX
sound (continued) sound effects integrating into Web pages, 211213 overview, 209 transitions sounds, 209211 <source> tag, 204 <source> tag codex parameter, 205206 overview, 204 type attribute, 204205 span element, 54 Spanish language attribute value, 34 spans (table), 122125 src attribute, 44, 226 storage local, 316320 overview, 311312 practice examples, 321322 session, 312316 temporary data, 332333 storing temporary values arrays, 248249 creating objects, 250251 DOM and browser effects, 251252 objects, 249250 overview, 244 types of data, 245246 variables, 244245, 246247 story class, 110112 streaming video, 215 string, 245 structure HTML5, 4952 PHP program arrays, 334335 constants, 333334 objects, 335336 properties, 335336 temporary data storage, 332333 variables, 333 Web page, 4749 style adding to canvas drawings, 262264 adding to text with CSS3 embedded style sheets, 5354 external style sheets, 5558 inline style, 5859 styling HTML5 elements with CSS3 properties, 5253 style sheets alternate, 128131 embedded, 5354 external, 5557 using with different browsers, 130 <style> tag, 5253 styling tables adding borders with CSS3, 114117 data clarification with background colors, 117119 subtraction () operator, 337 SVG (Scalable Vector Graphics), 175177, 186187, 194196 Switch Sound File Converter, 208 controls, 200202 converting files, 208 creating files, 206209 loop, 203 overview, 199200 practice examples, 214 preload attribute, 202203 sound effects, 209213 <source> tag, 204 <base>, 8687 <body>, 3233, 86 <br>, 4546
<canvas>
T
tables complex
colspan attribute, 120122 overview, 120 rowspan attribute, 120122 CSS3 table properties for HTML5, 110112 elements, 113 overview, 109 practical spans, 122125 practice examples, 125126 styling adding borders with CSS3, 114117 data clarification with background colors, 117119 tabular data, 109, 112114 tabular data defined, 109 overview, 112114 tags <a>. see links <audio>
354
Apple Safari support, 203 autoplay attribute, 200 browser support for, 203204
adding styles, 262264 creating drawings, 258260, 269281 grid, 256257 images, 264269 implementation, 256 overview, 253256 practice examples, 281 removing drawings, 262264 scripts, 8990 setting up drawings, 257258 transparency, 74 working with multiple drawings, 260262 <caption>, 113114 <center>, 1617 <comment>, 3538 creating, 89 discontinued, 1517 <div>, 9498 <figcaption>, 100103 <figure>, 100103 <form>, 242244 <head>, 32, 86 <hgroup>, 5052 how they work basic HTML tag, 32 comment tag, 3538 describing pages with tags, 3233 identifying parts of tags, 3334 language attribute, 3435 overview, 31 <hr>, 99100 <html>, 86 HTML4, 1115
INDEX
<img>, 44 <meta>, 44, 86, 8788
nesting, 3840 <output>, 242244 overview, 27 <p>, 35, 9498 parsing code fixing TextEdit on Macintosh, 30 fixing Windows default file extension settings, 29 how files work with Web, 31 HTML5 and related files, 28 overview, 28 practice examples, 2526, 4041 refreshing, 88 <script>, 8990 <select>, 153156
<source>
TextEdit, fixing on Macintosh, 30 3GP video format, 217, 221222 thumbnail icons, 167169 Tidwell, Jennifer (author) Designing Interfaces, 148 work on grouping elements, 159160 title attribute, 133 <tr> tag, 14 transition sounds, 209211 transparency, adding to color, 7476 Tufte, Edward (informationdesign thinker), 114115, 148 type attribute, 133, 204205
U
URL keyboards, datalist elements on, 296297 URL type, 294 user navigation, 148149
codex parameter, 205206 overview, 204 type attribute, 204205 <style>, 5253 <tr>, 14
<video> autoplay attribute, 228
V
values assigning to preload attribute, 202203 defined, 33 values (color) adding transparency to color, 7476 creating color schemes, 7478 integrating color palettes with Web pages, 7881 practice examples, 81 RGB color hexadecimal settings, 7174 names, 6667 overview, 66 RGB and HSL percentages, 6769 RGB decimal integer settings, 7071 values (temporary), storing arrays, 248249 creating objects, 250251 DOM and browser effects, 251252
browser compatibility, 218222 controls attribute, 228229 creating for Web, 223225 creating Web pages with, 216218 height attribute, 229 loop attribute, 227228 overview, 215, 225 poster attribute, 226227 practice examples, 229230 preload attribute, 227 src attribute, 226 width attribute, 229 <wbr>, 4546 target attribute, 140141, 290 temporary data storage, 332333 testing PHP, 327328 text, adding style to embedded style sheets, 5354 external style sheets, 5558 inline style, 5859 styling HTML5 elements with CSS3 properties, 5253
objects, 249250 overview, 244 types of data, 245246 variables, 244245, 246247 variables overview, 244245 PHP, 333 types of, 246247 vertical bar (|), 40 vertical navigation HTML5 mechanics of, 162165 overview, 160 video. see also audio autoplay attribute, 228 browser compatibility Adobe Media Encoder CS5, 221222 overview, 218219 WebM Miro Video Converter, 219220 controls attribute, 228229 creating for Web camcorders, 223224 overview, 222 screen video capture, 225 webcams, 223 creating Web pages with, 216218 height attribute, 229 loop attribute, 227228 overview, 215, 225 poster attribute, 226227 practice examples, 229230 preload attribute, 227 src attribute, 226 width attribute, 229 <video> tag. see video
355
W
W3C (World Wide Web Consortium), on tables, 110 <wbr> tag, 4546 Web camcorders, 223224 creating video for overview, 222 webcams, 223 design, 6364 files for, 31
INDEX
Web (continued) navigation concepts designer navigation, 148149 global navigation, 149156 overview, 148 user navigation, 148149 preserving layers in graphics, 178179 screen video capture, 225 Web pages adapting for mobile viewing, 310 adding metadata to, 8788 objects, 320 adding style to text with CSS3 embedded style sheets, 5354 external style sheets, 5558 inline style, 5859 styling HTML5 elements with CSS3 properties, 5253 adjusting objects, 321 anchors, 137140 calling with JavaScript, 156158 creating CSS3 classes, 5961 CSS3 IDs, 6263 overview, 216218, 307309 describing with tags, 3233 fundamentals of, 4445 HTML5 structure, 4952 inserting JavaScript into detecting events, 236237 event handlers, 236 external files, 234235 functions, 235 handling with elements, 237239 overview, 234 integrating color palette with, 7881 integrating sound into, 211213 links author relations, 135137 browsing contexts in computer browsers, 141142 browsing contexts in mobile browsers, 142143 hierarchical sequential link types, 137 overview, 134 page anchors, 137140 rel attribute, 134 targets, 140141 nesting, 144146 organizing designing in sections, 9194 figures and captions, 100103 files, 103106 grouping without fracturing, 99100 overview, 4547 paragraphs, divisions, and lists, 9498 practice examples, 106107 top of HTML5 document, 8690 overview, 43 pixel density, 58 placing maps on, 307 structure of, 4749 Web safe colors, 177 Web sites, single-page with iframes linking to graphics, 166167 on mobile devices, 169170 overview, 166 thumbnail icons, 167169 webcams, 223 WebM video format, 217, 219220 width attribute, 229 Windows finding file size in, 181 fixing default file settings, 29 installing PHP, 327 Microsoft Movie Maker, 223 Windows 7 Sound Recorder, 206207 World Wide Web Consortium (W3C), on tables, 110 write() function, 235
356