Sie sind auf Seite 1von 72

CSS3 2D Transforms

Search w3schools.com: Nyelv kivlas z ts a HOME HTML CSS JAVASCRIPT JQUERY XML ASP.NET PHP SQL MORE...
REFERENC ES | EXAMP LES | FO RUM

7/2/13

| ABO UT

SHARE T HIS PAGE

Like

70k

CSS3 Tutorial
CSS3 HOME CSS3 Introduction CSS3 Borders CSS3 Backgrounds CSS3 Text Effects CSS3 Fonts CSS3 2D T ransforms CSS3 3D Transforms CSS3 Transitions CSS3 Animations CSS3 Multiple Columns CSS3 User Interface

CSS3 2D Transforms
Previous Next Chapter

WEB HOST ING


Bes t Web Ho s ting eUK Web Ho s ting UK Res eller Ho s ting Clo ud Ho s ting

CSS3 Transforms
With CSS3 transform, we can move, scale, turn, spin, and stretch elements.

WEB BUILDING
Do wnlo ad XML Edito r FREE Webs ite BUILDER FREE Webs ite Creato r Bes t Webs ite Templates

CSS3 References
CSS3 Reference CSS3 Browser Support CSS3 Selectors CSS3 Reference Aural CSS3 Web Safe Fonts CSS3 Units CSS3 Colors CSS3 Color Values CSS3 Color Names CSS3 Color HEX

How Does it Work?


A transform is an effect that lets an element change shape, size and position. You can transform your elements using 2D or 3D transformation.

ST AT IST ICS
Bro ws er Statis tic s OS Statis tic s Dis play Statis tic s

Browser Support
Propert y transform Internet Explorer 10, Firefox, and Opera support the transform property. Chrome and Safari requires the prefix -webkit-. Not e: Internet Explorer 9 requires the prefix -ms-. Browser Support

2D Transforms
In this chapter you will learn about the 2d transform methods: translate() rotate() scale() skew() matrix() You will learn about 3D transforms in the next chapter.

Example
div { transform: rotate(30deg); -ms-transform: rotate(30deg); /* IE 9 */ -webkit-transform: rotate(30deg); /* Safari and Chrome */ }
T ry it yourself

The translate() Method

With the translate() method, the element moves from its current position, depending on the parameters given for the left (X-axis) and the top (Y-axis) position:

Example
div { transform: translate(50px,100px); -ms-transform: translate(50px,100px); /* IE 9 */ -webkit-transform: translate(50px,100px); /* Safari and Chrome */ }
T ry it yourself

http://www.w3schools.com/css3/css3_2dtransforms.asp

1 / 72

CSS3 2D Transforms
The value translate(50px,100px) moves the element 50 pixels from the left, and 100 pixels from the top.

7/2/13

The rotate() Method

With the rotate() method, the element rotates clockwise at a given degree. Negative values are allowed and rotates the element counter-clockwise.

Example
div { transform: rotate(30deg); -ms-transform: rotate(30deg); /* IE 9 */ -webkit-transform: rotate(30deg); /* Safari and Chrome */ }
T ry it yourself The value rotate(30deg) rotates the element clockwise 30 degrees.

The scale() Method

With the scale() method, the element increases or decreases the size, depending on the parameters given for the width (X-axis) and the height (Y-axis):

Example
div { transform: scale(2,4); -ms-transform: scale(2,4); /* IE 9 */ -webkit-transform: scale(2,4); /* Safari and Chrome */ }
T ry it yourself The value scale(2,4) transforms the width to be twice its original size, and the height 4 times its original size.

The skew() Method

With the skew() method, the element turns in a given angle, depending on the parameters given for the horizontal (X-axis) and the vertical (Y-axis) lines:

Example
div { transform: skew(30deg,20deg); -ms-transform: skew(30deg,20deg); /* IE 9 */ -webkit-transform: skew(30deg,20deg); /* Safari and Chrome */ }
T ry it yourself The value skew(30deg,20deg) turns the element 30 degrees around the X-axis, and 20 degrees around the Y-axis.

The matrix() Method

The matrix() method combines all of the 2D transform methods into one.

http://www.w3schools.com/css3/css3_2dtransforms.asp

2 / 72

CSS3 2D Transforms
The matrix method take six parameters, containing mathematic functions, which allows you to: rotate, scale, move (translate), and skew elements.

7/2/13

Example
How to rotate a div element 30 degrees, using the matrix method:

div { transform:matrix(0.866,0.5,-0.5,0.866,0,0); -ms-transform:matrix(0.866,0.5,-0.5,0.866,0,0); /* IE 9 */ -webkit-transform:matrix(0.866,0.5,-0.5,0.866,0,0); /* Safari and Chrome */ }


T ry it yourself

New Transform Properties


The following table lists all the transform properties: Propert y transform transform-origin Descript ion Applies a 2D or 3D transformation to an element Allows you to change the position on transformed elements CSS 3 3

2D Transform Methods
Funct ion matrix(n,n,n,n,n,n ) translate(x,y) translateX(n ) translateY(n ) scale(x,y) scaleX(n ) scaleY(n ) rotate(angle) skew(x-angle,y-angle) skewX(angle) skewY(angle) Descript ion Defines a 2D transformation, using a matrix of six values Defines a 2D translation, moving the element along the X- and the Y-axis Defines a 2D translation, moving the element along the X-axis Defines a 2D translation, moving the element along the Y-axis Defines a 2D scale transformation, changing the elements width and height Defines a 2D scale transformation, changing the element's width Defines a 2D scale transformation, changing the element's height Defines a 2D rotation, the angle is specified in the parameter Defines a 2D skew transformation along the X- and the Y-axis Defines a 2D skew transformation along the X-axis Defines a 2D skew transformation along the Y-axis

Previous

Next Chapter

T o p 10 T ut o rials
HTML Tuto rial HTML5 Tuto rial CSS Tuto rial CSS3 Tuto rial JavaSc ript Tuto rial jQuery Tuto rial SQL Tuto rial PHP Tuto rial ASP.NET Tuto rial XML Tuto rial

T o p 10 References
HTML/HTML5 Referenc e CSS 1,2,3 Referenc e CSS 3 Bro ws er Suppo rt JavaSc ript HTML DOM XML DOM PHP Referenc e jQuery Referenc e ASP.NET Referenc e HTML Co lo rs

Examples
HTML Examples CSS Examples XML Examples JavaSc ript Examples HTML DOM Examples XML DOM Examples AJAX Examples ASP.NET Examples Raz o r Examples ASP Examples SVG Examples

Quizzes
HTML Quiz HTML5 Quiz XHTML Quiz CSS Quiz JavaSc ript Quiz jQuery Quiz XML Quiz ASP Quiz PHP Quiz SQL Quiz

Co lo r Picker

St at ist ics
Bro ws er Statis tic s Bro ws er OS Bro ws er Dis play

REPO RT ERRO R

| HO ME

| TO P

| PRINT

| FO RUM

| ABO UT

| AD VERTISE WITH US

W3Sc ho o ls is o ptimiz ed fo r learning, tes ting, and training. Examples might be s implified to impro ve reading and bas ic unders tanding. Tuto rials , referenc es , and examples are c o ns tantly reviewed to avo id erro rs , but we c anno t warrant full c o rrec tnes s o f all c o ntent. While us ing this s ite, yo u agree to have read and ac c epted o ur terms o f us e and privac y po lic y. Co pyright 1999-2013 by Refs nes Data. All Rights Res erved.

http://www.w3schools.com/css3/css3_2dtransforms.asp

3 / 72

Semantics - Dive Into HTML5

7/2/13

Yo u are here: Ho me Dive Into HTML5

WHAT DOES IT ALL MEAN?


sho w table o f co ntents

DIVING IN

his chapter will take an HTML page that has abso lutely no thing wro ng with it, and impro ve it. Parts o f it will beco me sho rter. Parts will beco me lo nger. All o f it will beco me mo re semantic. Itll be aweso me.

Here is the page in questio n. Learn it. Live it. Lo ve it. Open it in a new tab and do nt co me back until yo uve hit View So urce at least o nce.

THE DOCTYPE
Fro m the to p: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> This is called the do ctype. Theres a lo ng histo ry and a black art behind the do ctype. While wo rking o n Internet Explo rer 5 fo r Mac, the develo pers at Micro so ft fo und themselves with a surprising pro blem. The upco ming versio n o f their bro wser had impro ved its standards suppo rt so much, o lder pages no lo nger rendered pro perly. Or rather, they rendered pro perly (acco rding to specificatio ns), but peo ple expected them to render improperly. The pages themselves had been autho red based o n the quirks o f the do minant bro wsers o f the day, primarily Netscape 4 and Internet Explo rer 4. IE5/Mac was so advanced, it actually bro ke the web. Micro so ft came up with a no vel so lutio n. Befo re rendering a page, IE5/Mac lo o ked at the do ctype, which is typically the first line o f the HTML so urce (even befo re the <html> element). Older pages (that relied o n the rendering quirks o f o lder bro wsers) generally didnt have a do ctype at all. IE5/Mac rendered these pages like o lder bro wsers did. In o rder to activate the new standards suppo rt, web page autho rs had to o pt in, by supplying the right do ctype befo re the <html> element. This idea spread like wildfire, and so o n all majo r bro wsers had two mo des: quirks mo de and standards mo de. Of co urse, this being the web, things quickly go t o ut o f hand. When Mo zilla tried to ship versio n 1.1 o f their bro wser, they disco vered that there were pages being rendered in standards mo de that were actually relying o n o ne specific quirk. Mo zilla had just fixed its rendering engine to eliminate this quirk, and tho usands o f pages bro ke all at o nce. Thus was created and I am no t making this up almo st standards mo de. In his seminal wo rk, Activating Bro wser Mo des with Do ctype, Henri Sivo nen summarizes the different mo des: Quirks Mo de In the Quirks mo de, bro wsers vio late co ntempo rary Web fo rmat specificatio ns in o rder to avo id breaking pages autho red acco rding to practices that were prevalent in the late 1990s. Standards Mo de In the Standards mo de, bro wsers try to give co nfo rming do cuments the specificatio n-wise co rrect treatment to the extent implemented in a particular bro wser. HTML5 calls this mo de the no quirks mo de.
http://diveintohtml5.info/semantics.html#nav-element 4 / 72

Semantics - Dive Into HTML5

7/2/13

Almo st Standards Mo de Firefo x, Safari, Chro me, Opera (since 7.5) and IE8 also have a mo de kno wn as Almo st Standards mo de, that implements the vertical sizing o f table cells traditio nally and no t rigo ro usly acco rding to the CSS2 specificatio n. HTML5 calls this mo de the limited quirks mo de. (Yo u sho uld read the rest o f Henris article, because Im simplifying immensely here. Even in IE5/Mac, there were a few o lder do ctypes that didnt co unt as far as o pting into standards suppo rt. Over time, the list o f quirks grew, and so did the list o f do ctypes that triggered quirks mo de. The last time I tried to co unt, there were 5 do ctypes that triggered almo st standards mo de, and 73 that triggered quirks mo de. But I pro bably missed so me, and Im no t even go ing to talk abo ut the crazy things that Internet Explo rer 8 do es to switch between its fo ur fo ur! different rendering mo des. Heres a flo wchart. Kill it. Kill it with fire.) No w then. Where were we? Ah yes, the do ctype: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> That happens to be o ne o f the 15 do ctypes that trigger standards mo de in all mo dern bro wsers. There is no thing wro ng with it. If yo u like it, yo u can keep it. Or yo u can change it to the HTML5 do ctype, which is sho rter and sweeter and also triggers standards mo de in all mo dern bro wsers. This is the HTML5 do ctype: <!DOCTYPE html> Thats it. Just 15 characters. Its so easy, yo u can type it by hand and no t screw it up.

THE ROOT ELEMENT


An HTML page is a series o f nested elements. The entire structure o f the page is like a tree. So me elements are siblings, like two branches that extend fro m the same tree trunk. So me elements can be children o f o ther elements, like a smaller branch that extends fro m a larger branch. (It wo rks the o ther way to o ; an element that co ntains o ther elements is called the parent no de o f its immediate child elements, and the ancesto r o f its grandchildren.) Elements that have no children are called leaf no des. The o uter-mo st element, which is the ancesto r o f all o ther elements o n the page, is called the ro o t element. The ro o t element o f an HTML page is always <html>. In this example page, the ro o t element lo o ks like this:

<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">

There is no thing wro ng with this markup. Again, if yo u like it, yo u can keep it. It is valid HTML5. But parts o f it are no lo nger necessary in HTML5, so yo u can save a few bytes by remo ving them. The first thing to discuss is the xmlns attribute. This is a vestige o f XHTML 1.0. It says that elements in this page are in the XHTML namespace, http://www.w3.org/1999/xhtml. But elements in HTML5 are always in this namespace, so yo u no lo nger need to declare it explicitly. Yo ur HTML5 page will wo rk exactly the same in all bro wsers, whether this attribute is present o r no t.
http://diveintohtml5.info/semantics.html#nav-element 5 / 72

Semantics - Dive Into HTML5

7/2/13

Dro pping the xmlns attribute leaves us with this ro o t element: <html lang="en" xml:lang="en"> The two attributes here, lang and xml:lang, bo th define the language o f this HTML page. (en stands fo r English. No t writing in English? Find yo ur language co de.) Why two attributes fo r the same thing? Again, this is a vestige o f XHTML. Only the lang attribute has any effect in HTML5. Yo u can keep the xml:lang attribute if yo u like, but if yo u do , yo u need to ensure that it co ntains the same value as the lang attribute. To ease migratio n to and fro m XHTML, autho rs may specify an attribute in no namespace with no prefix and with the literal lo calname "xml:lang" o n HTML elements in HTML do cuments, but such attributes must o nly be specified if a lang attribute in no namespace is also specified, and bo th attributes must have the same value when co mpared in an ASCII case-insensitive manner. The attribute in no namespace with no prefix and with the literal lo calname "xml:lang" has no effect o n language pro cessing. Are yo u ready to dro p it? Its OK, just let it go . Go ing, go ing go ne! That leaves us with this ro o t element: <html lang="en"> And thats all I have to say abo ut that.

THE <HEAD> ELEMENT

The first child o f the ro o t element is usually the <head> element. The <head> element co ntains metadata info rmatio n about the page, rather than the bo dy o f the page itself. (The bo dy o f the page is, unsurprisingly, co ntained in the <body> element.) The <head> element itself is rather bo ring, and it hasnt changed in any interesting way in HTML5. The go o d stuff is whats inside the <head> element. And fo r that, we turn o nce again to o ur example page: <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>My Weblog</title> <link rel="stylesheet" type="text/css" href="style-original.css" /> <link rel="alternate" type="application/atom+xml" title="My Weblog feed" href="/feed/" /> <link rel="search" type="application/opensearchdescription+xml" title="My Weblog search" href="opensearch.xml" /> <link rel="shortcut icon" href="/favicon.ico" /> </head> First up: the <meta> element.
http://diveintohtml5.info/semantics.html#nav-element 6 / 72

Semantics - Dive Into HTML5

7/2/13

CHARACTER ENCODING
When yo u think o f text, yo u pro bably think o f characters and symbo ls I see o n my co mputer screen. But co mputers do nt deal in characters and symbo ls; they deal in bits and bytes. Every piece o f text yo uve ever seen o n a co mputer screen is actually sto red in a particular character encoding . There are hundreds o f different character enco dings, so me o ptimized fo r particular languages like Russian o r Chinese o r English, and o thers that can be used fo r multiple languages. Ro ughly speaking, the character enco ding pro vides a mapping between the stuff yo u see o n yo ur screen and the stuff yo ur co mputer actually sto res in memo ry and o n disk. In reality, its mo re co mplicated than that. The same character might appear in mo re than o ne enco ding, but each enco ding might use a different sequence o f bytes to actually sto re the character in memo ry o r o n disk. So , yo u can think o f the character enco ding as a kind o f decryptio n key fo r the text. Whenever so meo ne gives yo u a sequence o f bytes and claims its text, yo u need to kno w what character enco ding they used so yo u can deco de the bytes into characters and display them (o r pro cess them, o r whatever). So , ho w do es yo ur bro wser actually determine the character enco ding o f the stream o f bytes that a web server sends? Im glad yo u asked. If yo ure familiar with HTTP headers, yo u may have seen a header like this: Content-Type: text/html; charset="utf-8" Briefly, this says that the web server thinks its sending yo u an HTML do cument, and that it thinks the do cument uses the UTF-8 character enco ding. Unfo rtunately, in the who le magnificent so up o f the Wo rld Wide Web, few autho rs actually have co ntro l o ver their HTTP server. Think Blo gger: the co ntent is pro vided by individuals, but the servers are run by Go o gle. So HTML 4 pro vided a way to specify the character enco ding in the HTML do cument itself. Yo uve pro bably seen this to o : <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> Briefly, this says that the web autho r thinks they have autho red an HTML do cument using the UTF-8 character enco ding. Bo th o f these techniques still wo rk in HTML5. The HTTP header is the preferred metho d, and it o verrides the <meta> tag if present. But no t everyo ne can set HTTP headers, so the <meta> tag is still aro und. In fact, it go t a little easier in HTML5. No w it lo o ks like this: <meta charset="utf-8" /> This wo rks in all bro wsers. Ho w did this sho rtened syntax co me abo ut? Here is the best explanatio n I co uld find: The ratio nale fo r the <meta charset> attribute co mbinatio n is that UAs already implement it, because peo ple tend to leave things unquo ted, like: <META HTTP-EQUIV="Content-Type" CONTENT="text/html;" charset="ISO-8859-1"> There are even a few <meta charset> test cases if yo u do nt believe that bro wsers already do this.

ASK PRO FESSO R MARKUP

Q: I never use funny characters. Do I still need to declare my character enco ding? A: Yes! Yo u sho uld always specify a character enco ding o n every HTML page yo u serve. No t specifying an enco ding can lead to security vulnerabilities.

http://diveintohtml5.info/semantics.html#nav-element

7 / 72

Semantics - Dive Into HTML5

7/2/13

To sum up: character enco ding is co mplicated, and it has no t been made any easier by decades o f po o rly written so ftware used by co py-and-pasteeducated autho rs. Yo u sho uld always specify a character enco ding o n e ve ry HTML do cument, o r bad things will happen. Yo u can do it with the HTTP Content-Type header, the <meta http-equiv> declaratio n, o r the sho rter <meta charset> declaratio n, but please do it. The web thanks yo u.

FRIENDS & (LINK) RELATIONS


Regular links (<a href>) simply po int to ano ther page. Link relatio ns are a way to explain why yo ure po inting to ano ther page. They finish the sentence Im po inting to this o ther page because... ...its a stylesheet co ntaining CSS rules that yo ur bro wser sho uld apply to this do cument. ...its a feed that co ntains the same co ntent as this page, but in a standard subscribable fo rmat. ...its a translatio n o f this page into ano ther language. ...its the same co ntent as this page, but in PDF fo rmat. ...its the next chapter o f an o nline bo o k o f which this page is also a part. And so o n. HTML5 breaks link relatio ns into two catego ries: Two catego ries o f links can be created using the link element. Links t o e xt e rnal re so urce s are links to reso urces that are to be used to augment the current do cument, and hype rlink links are links to o ther do cuments. ... The exact behavio r fo r links to external reso urces depends o n the exact relatio nship, as defined fo r the relevant link type. Of the examples I just gave, o nly the first (rel="stylesheet") is a link to an external reso urce. The rest are hyperlinks to o ther do cuments. Yo u may wish to fo llo w tho se links, o r yo u may no t, but theyre no t required in o rder to view the current page. Mo st o ften, link relatio ns are seen o n <link> elements within the <head> o f a page. So me link relatio ns can also be used o n <a> elements, but this is unco mmo n even when allo wed. HTML5 also allo ws so me relatio ns o n <area> elements, but this is even less co mmo n. (HTML 4 did no t allo w a rel attribute o n <area> elements.) See the full chart o f link relatio ns to check where yo u can use specific rel values.

ASK PRO FESSO R MARKUP

Q: Can I make up my o wn link relatio ns? A: There seems to be an infinite supply o f ideas fo r new link relatio ns. In an attempt to prevent peo ple fro m just making stuff up, the micro fo rmats co mmunity maintains a registry o f pro po sed rel values and the HTML specificatio n defines the pro cess fo r getting them accepted.

REL = STYLESHEET
Lets lo o k at the first link relatio n in o ur example page: <link rel="stylesheet" href="style-original.css" type="text/css" /> This is the mo st frequently used link relatio n in the wo rld (literally). <link rel="stylesheet"> is fo r po inting to CSS rules that are sto red in a separate file. One small o ptimizatio n yo u can make in HTML5 is to dro p the type attribute.
http://diveintohtml5.info/semantics.html#nav-element 8 / 72

Semantics - Dive Into HTML5

7/2/13

Theres o nly o ne stylesheet language fo r the web, CSS, so thats the default value fo r the type attribute. This wo rks in all bro wsers. (I suppo se so meo ne co uld invent a new stylesheet language so meday, but if that happens, just add the type attribute back.) <link rel="stylesheet" href="style-original.css" />

REL = ALTERNATE
Co ntinuing with o ur example page: <link rel="alternate" type="application/atom+xml" title="My Weblog feed" href="/feed/" /> This link relatio n is also quite co mmo n. <link rel="alternate">, co mbined with either the RSS o r Ato m media type in the type attribute, enables so mething called feed auto disco very. It allo ws syndicated feed readers (like Go o gle Reader) to disco ver that a site has a news feed o f the latest articles. So me bro wsers also suppo rt feed auto disco very by displaying a special ico n next to the URL. (Unlike with rel="stylesheet", the type attribute matters here. Do nt dro p it!) The rel="alternate" link relatio n has always been a strange hybrid o f use cases, even in HTML 4. In HTML5, its definitio n has been clarified and extended to mo re accurately describe existing web co ntent. As yo u just saw, using rel="alternate" in co njunctio n with type=application/atom+xml indicates an Ato m feed fo r the current page. But yo u can also use rel="alternate" in co njunctio n with o ther type attributes to indicate the same co ntent in ano ther fo rmat, like PDF. HTML5 also puts to rest a lo ng-standing co nfusio n abo ut ho w to link to translatio ns o f do cuments. HTML 4 says to use the lang attribute in co njunctio n with rel="alternate" to specify the language o f the linked do cument, but this is inco rrect. The HTML 4 Errata do cument lists fo ur o utright erro rs in the HTML 4 specificatio n. One o f these o utright erro rs is ho w to specify the language o f a do cument linked with rel="alternate" The co rrect way, described in the HTML 4 Errata and no w in HTML5, is to use the hreflang attribute. Unfo rtunately, these errata were never re-integrated into the HTML 4 spec, because no o ne in the W3C HTML Wo rking Gro up was wo rking o n HTML anymo re.

OTHER LINK RELATIONS IN HTML5


rel="author" is used to link to info rmatio n abo ut the autho r o f the page. This can be a mailto: address, tho ugh it do esnt have to be. It co uld simply link to a co ntact fo rm o r abo ut the autho r page. HTML 4 defined rel="start", rel="prev", and rel="next" to define relatio ns between pages that are part o f a series (like chapters o f a bo o k, o r even po sts o n a blo g). The o nly o ne that was ever used co rrectly was rel="next". Peo ple used rel="previous" instead o f rel="prev"; they used rel="begin" and rel="first" instead o f rel="start"; they used rel="end" instead o f rel="last". Oh, and all by themselves they made up rel="up" to po int to a parent page. The best way to think o f rel="up" is to lo o k at yo ur breadcrumb navigatio n (o r at least imagine it). Yo ur ho me page is pro bably the first page in yo ur breadcrumbs, and the current page is at the tail end. rel="up" po ints to the next-to -last page in the breadcrumbs. HTML5 includes rel="next" and rel="prev", just like HTML 4, and suppo rts rel="previous" fo r backward co mpatibility. The specificatio n o nce had rel="first", rel="last", and rel="up", to o . Ho wever, based o n the lack o f interest fro m implemento rs and users the HTML Wo rking Gro up decided to dro p these values fro m the specificatio n.

http://diveintohtml5.info/semantics.html#nav-element

9 / 72

Semantics - Dive Into HTML5

7/2/13

rel="ico n" is the seco nd mo st po pular link relatio n, after rel="stylesheet". It is usually fo und to gether with shortcut, like so : <link rel="shortcut icon" href="/favicon.ico"> All majo r bro wsers suppo rt this usage to asso ciate a small ico n with the page. Usually its displayed in the bro wsers lo catio n bar next to the URL, o r in the bro wser tab, o r bo th. Also new in HTML5: the sizes attribute can be used in co njunctio n with the icon relatio nship to indicate the size o f the referenced ico n. rel="license" was invented by the micro fo rmats co mmunity. It indicates that the referenced do cument pro vides the co pyright license terms under which the current do cument is pro vided. rel="no fo llo w" indicates that the link is no t endo rsed by the o riginal autho r o r publisher o f the page, o r that the link to the referenced do cument was included primarily because o f a co mmercial relatio nship between peo ple affiliated with the two pages. It was invented by Go o gle and standardized within the micro fo rmats co mmunity. Wo rdPress adds rel="nofollow" to links added by co mmenters. The thinking was that if no fo llo w links did no t pass o n PageRank, spammers wo uld give up trying to po st spam co mments o n weblo gs. That didnt happen, but rel="nofollow" persists. rel="no referrer" indicates that no referrer info rmatio n is to be leaked when fo llo wing the link. WebKit suppo rts rel="no referrer" so it wo rks o n Go o gle Cho me and Safari (and ho pefully o n o ther WebKit-based bro wsers). [rel="no referrer" test case] rel="prefetch" indicates that preemptively fetching and caching the specified reso urce is likely to be beneficial, as it is highly likely that the user will require this reso urce. Search engines so metimes add <link rel="prefetch" href="URL of top search result"> to the search results page if they feel that the to p result is wildly mo re po pular than any o ther. Fo r example: using Firefo x, search Go o gle fo r CNN, view the page so urce, and search fo r the keywo rd prefetch. Mo zilla Firefo x is the o nly current bro wser that suppo rts rel="prefetch". rel="search" indicates that the referenced do cument pro vides an interface specifically fo r searching the do cument and its related reso urces. Specifically, if yo u want rel="search" to do anything useful, it sho uld po int to an OpenSearch do cument that describes ho w a bro wser co uld co nstruct a URL to search the current site fo r a given keywo rd. OpenSearch (and rel="search" links that po int to OpenSearch descriptio n do cuments) has been suppo rted in Internet Explo rer since versio n 7, Mo zilla Firefo x since versio n 2, and Go o gle Chro me. rel="tag" indicates that the tag that the referenced do cument represents applies to the current do cument. Marking up tags (catego ry keywo rds) with the rel attribute was invented by Techno rati to help them catego rize blo g po sts. Early blo gs and tuto rials thus referred to them as Techno rati tags. (Yo u read that right: a co mmercial co mpany co nvinced the entire wo rld to add metadata that made the co mpanys jo b easier. Nice wo rk if yo u can get it!) The syntax was later standardized within the micro fo rmats co mmunity, where it was simply called rel="tag". Mo st blo gging systems that allo w asso ciating catego ries, keywo rds, o r tags with individual po sts will mark them up with rel="tag" links. Bro wsers do no t do anything special with them; theyre really designed fo r search engines to use as a signal o f what the page is abo ut.

NEW SEMANTIC ELEMENTS IN HTML5


HTML5 is no t just abo ut making existing markup sho rter (altho ugh it do es a fair amo unt o f that). It also defines new semantic elements. <section> The section element represents a generic do cument o r applicatio n sectio n. A sectio n, in this co ntext, is a thematic gro uping o f co ntent, typically with a heading. Examples o f sectio ns wo uld be chapters, the tabbed pages in a tabbed dialo g bo x, o r the numbered sectio ns o f a thesis. A Web site's ho me page co uld be split
http://diveintohtml5.info/semantics.html#nav-element 10 / 72

Semantics - Dive Into HTML5

7/2/13

into sectio ns fo r an intro ductio n, news items, co ntact info rmatio n. <nav> The nav element represents a sectio n o f a page that links to o ther pages o r to parts within the page: a sectio n with navigatio n links. No t all gro ups o f links o n a page need to be in a nav element o nly sectio ns that co nsist o f majo r navigatio n blo cks are appro priate fo r the nav element. In particular, it is co mmo n fo r fo o ters to have a sho rt list o f links to co mmo n pages o f a site, such as the terms o f service, the ho me page, and a co pyright page. The footer element alo ne is sufficient fo r such cases, witho ut a nav element. <article> The article element represents a co mpo nent o f a page that co nsists o f a self-co ntained co mpo sitio n in a do cument, page, applicatio n, o r site and that is intended to be independently distributable o r reusable, e.g. in syndicatio n. This co uld be a fo rum po st, a magazine o r newspaper article, a Web lo g entry, a usersubmitted co mment, an interactive widget o r gadget, o r any o ther independent item o f co ntent. <aside> The aside element represents a sectio n o f a page that co nsists o f co ntent that is tangentially related to the co ntent aro und the aside element, and which co uld be co nsidered separate fro m that co ntent. Such sectio ns are o ften represented as sidebars in printed typo graphy. The element can be used fo r typo graphical effects like pull quo tes o r sidebars, fo r advertising, fo r gro ups o f nav elements, and fo r o ther co ntent that is co nsidered separate fro m the main co ntent o f the page. <hgroup> The hgroup element represents the heading o f a sectio n. The element is used to gro up a set o f h1 h6 elements when the heading has multiple levels, such as subheadings, alternative titles, o r taglines. <header> The header element represents a gro up o f intro ducto ry o r navigatio nal aids. A header element is intended to usually co ntain the sectio ns heading (an h1 h6 element o r an hgroup element), but this is no t required. The header element can also be used to wrap a sectio ns table o f co ntents, a search fo rm, o r any relevant lo go s. <footer> The footer element represents a fo o ter fo r its nearest ancesto r sectio ning co ntent o r sectio ning ro o t element. A fo o ter typically co ntains info rmatio n abo ut its sectio n such as who wro te it, links to related do cuments, co pyright data, and the like. Fo o ters do nt necessarily have to appear at the end o f a sectio n, tho ugh they usually do . When the footer element co ntains entire sectio ns, they represent appendices, indexes, lo ng co lo pho ns, verbo se license agreements, and o ther such co ntent. <time> The time element represents either a time o n a 24 ho ur clo ck, o r a precise date in the pro leptic Grego rian calendar, o ptio nally with a time and a time-zo ne o ffset. <mark> The mark element represents a run o f text in o ne do cument marked o r highlighted fo r reference purpo ses.

I kno w yo ure anxio us to start using these new elements, o therwise yo u wo uldnt be reading this chapter. But first we need to take a little deto ur.

A LONG DIGRESSION INTO HOW BROWSERS HANDLE UNKNOWN ELEMENTS


Every bro wser has a master list o f HTML elements that it suppo rts. Fo r example, Mo zilla Firefo xs list is sto red in nsElementTable.cpp. Elements no t in this list are treated as unkno wn elements. There are two fundamental pro blems with unkno wn elements: 1. Ho w sho uld t he e le m e nt be st yle d? By default, <p> has spacing o n the to p and bo tto m, <blockquote> is indented with a left margin, and <h1> is displayed in a larger fo nt. But what default styles sho uld be applied to unkno wn elements? 2. What sho uld t he e le m e nt s DOM lo o k like ? Mo zillas nsElementTable.cpp includes info rmatio n abo ut what
http://diveintohtml5.info/semantics.html#nav-element 11 / 72

Semantics - Dive Into HTML5

7/2/13

kinds o f o ther elements each element can co ntain. If yo u include markup like <p><p>, the seco nd paragraph element implicitly clo ses the first o ne, so the elements end up as siblings, no t parent-and-child. But if yo u write <p><span>, the span do es no t clo se the paragraph, because Firefo x kno ws that <p> is a blo ck element that can co ntain the inline element <span>. So , the <span> ends up as a child o f the <p> in the DOM. Different bro wsers answer these questio ns in different ways. (Sho cking, I kno w.) Of the majo r bro wsers, Micro so ft Internet Explo rers answer to bo th questio ns is the mo st pro blematic, but every bro wser needs a little bit o f help here. The first questio n sho uld be relatively simple to answer: do nt give any special styling to unkno wn elements. Just let them inherit whatever CSS pro perties are in effect wherever they appear o n the page, and let the page autho r specify all styling with CSS. And that wo rks, mo stly, but theres o ne little go tcha yo u need to be aware o f.

PRO FESSO R MARKUP SAYS

All bro wsers render unkno wn elements inline, i.e. as if they had a display:inline CSS rule.

There are several new elements defined in HTML5 which are blo ck-level elements. That is, they can co ntain o ther blo cklevel elements, and HTML5-co mpliant bro wsers will style them as display:block by default. If yo u want to use these elements in o lder bro wsers, yo u will need to define the display style manually: article,aside,details,figcaption,figure, footer,header,hgroup,menu,nav,section { display:block; } (This co de is lifted fro m Rich Clarks HTML5 Reset Stylesheet, which do es many o ther things that are beyo nd the sco pe o f this chapter.) But wait, it gets wo rse! Prio r to versio n 9, Internet Explo rer did no t apply any styling o n unkno wn elements. Fo r example, if yo u had this markup: <style type="text/css"> article { display: block; border: 1px solid red } </style> ... <article> <h1>Welcome to Initech</h1> <p>This is your <span>first day</span>.</p> </article> Internet Explo rer (up to and including IE 8) will no t treat the <article> element as a blo ck-level element, no r will it put a red bo rder aro und the article. All the style rules are simply igno red. Internet Explo rer 9 fixes this pro blem. The seco nd pro blem is the DOM that bro wsers create when they enco unter unkno wn elements. Again, the mo st pro blematic bro wser is o lder versio ns o f Internet Explo rer (befo re versio n 9, which fixes this pro blem to o ). If IE 8 do esnt explicitly reco gnize the element name, it will insert the element into the DOM as an empty node with no children . All the elements that yo u wo uld expect to be direct children o f the unkno wn element will actually be inserted as siblings instead. Here is so me righteo us ASCII art to illustrate the difference. This is the DOM that HTML5 dictates: article |
http://diveintohtml5.info/semantics.html#nav-element 12 / 72

Semantics - Dive Into HTML5

7/2/13

+--h1 (child of article) | | | +--text node "Welcome to Initech" | +--p (child of article, sibling of h1) | +--text node "This is your " | +--span | | | +--text node "first day" | +--text node "." But this is the DOM that Internet Explo rer actually creates: article (no children) h1 (sibling of article) | +--text node "Welcome to Initech" p (sibling of h1) | +--text node "This is your " | +--span | | | +--text node "first day" | +--text node "." There is a wo ndero us wo rkaro und fo r this pro blem. If yo u create a dummy <article> element with JavaScript befo re yo u use it in yo ur page, Internet Explo rer will magically reco gnize the <article> element and let yo u style it with CSS. There is no need to ever insert the dummy element into the DOM. Simply creating the element o nce (per page) is eno ugh to teach IE to style the element it do esnt reco gnize. <html> <head> <style> article { display: block; border: 1px solid red } </style> <script>document.createElement("article");</script> </head> <body> <article> <h1>Welcome to Initech</h1> <p>This is your <span>first day</span>.</p> </article> </body> </html> This wo rks in all versio ns o f Internet Explo rer, all the way back to IE 6! We can extend this technique to create dummy co pies o f all the new HTML5 elements at o nce again, theyre never inserted into the DOM, so yo ull never see these dummy elements and then just start using them witho ut having to wo rry to o much abo ut no n-HTML5-capable bro wsers. Remy Sharp has do ne just that, with his aptly named HTML5 enabling script. The script has go ne thro ugh mo re than a
http://diveintohtml5.info/semantics.html#nav-element 13 / 72

Semantics - Dive Into HTML5

7/2/13

do zen revisio ns since I started writing this bo o k, but this is the basic idea: <!--[if lt IE 9]> <script> var e = ("abbr,article,aside,audio,canvas,datalist,details," + "figure,footer,header,hgroup,mark,menu,meter,nav,output," + "progress,section,time,video").split(','); for (var i = 0; i < e.length; i++) { document.createElement(e[i]); } </script> <![endif]--> The <!--[if lt IE 9]> and <![endif]--> bits are co nditio nal co mments. Internet Explo rer interprets them like an if statement: if the current bro wser is a versio n o f Internet Explo rer less than versio n 9, then execute this blo ck. Every o ther bro wser will treat the entire blo ck as an HTML co mment. The net result is that Internet Explo rer (up to and including versio n 8) will execute this script, but o ther bro wsers will igno re the script alto gether. This makes yo ur page lo ad faster in bro wsers that do nt need this hack. The JavaScript co de itself is relatively straightfo rward. The variable e ends up as an array o f strings like "abbr", "article", "aside", and so o n. Then we lo o p thro ugh this array and create each o f the named elements by calling document.createElement(). But since we igno re the return value, the elements are never inserted into the DOM. But this is eno ugh to get Internet Explo rer to treat these elements the way we want them to be treated, o nce we actually use them later in the page. That later bit is impo rtant. This script needs to be at the to p o f yo ur page, preferably in yo ur <head> element, no t at the bo tto m. That way, Internet Explo rer will execute the script before it parses yo ur tags and attributes. If yo u put this script at the bo tto m o f yo ur page, it will be to o late. Internet Explo rer will have already misinterpreted yo ur markup and co nstructed the wro ng DOM, and it wo nt go back and adjust it just because o f this script. Remy Sharp has minified this script and ho sted it o n Go o gle Pro ject Ho sting. (In case yo u were wo ndering, the script itself is o pen so urce and MIT-licensed, so yo u can use it in any pro ject.) If yo u like, yo u can even ho tlink the script by po inting directly to the ho sted versio n, like this: <head> <meta charset="utf-8" /> <title>My Weblog</title> <!--[if lt IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> No w were ready to start using the new semantic elements in HTML5.

HEADERS
Lets go back to o ur example page. Specifically, lets lo o k at just the headers: <div id="header"> <h1>My Weblog</h1> <p class="tagline">A lot of effort went into making this effortless.</p> </div>
http://diveintohtml5.info/semantics.html#nav-element 14 / 72

Semantics - Dive Into HTML5

7/2/13

<div class="entry"> <h2>Travel day</h2> </div> <div class="entry"> <h2>I'm going to Prague!</h2> </div> There is no thing wro ng with this markup. If yo u like it, yo u can keep it. It is valid HTML5. But HTML5 pro vides so me additio nal semantic elements fo r headers and sectio ns. First o ff, lets get rid o f that <div id="header">. This is a co mmo n pattern, but it do esnt mean anything. The div element has no defined semantics, and the id attribute has no defined semantics. (User agents are no t allo wed to infer any meaning fro m the value o f the id attribute.) Yo u co uld change this to <div id="shazbot"> and it wo uld have the same semantic value, i.e., no thing. HTML5 defines a <header> element fo r this purpo se. The HTML5 specificatio n has real-wo rld examples o f using the <header> element. Here is what it wo uld lo o k like o n o ur example page: <header> <h1>My Weblog</h1> <p class="tagline">A lot of effort went into making this effortless.</p> </header> Thats go o d. It tells anyo ne who wants to kno w that this is a header. But what abo ut that tagline? Ano ther co mmo n pattern, which up until no w had no standard markup. Its a difficult thing to mark up. A tagline is like a subheading, but its attached to the primary heading. That is, its a subheading that do esnt create its o wn sectio n. Header elements like <h1> and <h2> give yo ur page structure. Taken to gether, they create an o utline that yo u can use to visualize (o r navigate) yo ur page. Screenreaders use do cument o utlines to help blind users navigate thro ugh yo ur page. There are o nline to o ls and bro wser extensio ns that can help yo u visualize yo ur do cuments o utline. In HTML 4, <h1> <h6> elements were the only way to create a do cument o utline. The o utline o n the example page lo o ks like this: My Weblog (h1) | +--Travel day (h2) | +--I'm going to Prague! (h2) Thats fine, but it means that theres no way to mark up the tagline A lo t o f effo rt went into making this effo rtless. If we tried to mark it up as an <h2>, it wo uld add a phanto m no de to the do cument o utline: My Weblog (h1) | +--A lot of effort went into making this effortless. (h2) | +--Travel day (h2) |
http://diveintohtml5.info/semantics.html#nav-element 15 / 72

Semantics - Dive Into HTML5

7/2/13

+--I'm going to Prague! (h2) But thats no t the structure o f the do cument. The tagline do es no t represent a sectio n; its just a subheading. Perhaps we co uld mark up the tagline as an <h2> and mark up each article title as an <h3>? No , thats even wo rse: My Weblog (h1) | +--A lot of effort went into making this effortless. (h2) | +--Travel day (h3) | +--I'm going to Prague! (h3) No w we still have a phanto m no de in o ur do cument o utline, but it has sto len the children that rightfully belo ng to the ro o t no de. And herein lies the pro blem: HTML 4 do es no t pro vide a way to mark up a subheading witho ut adding it to the do cument o utline. No matter ho w we try to shift things aro und, A lo t o f effo rt went into making this effo rtless is go ing to end up in that graph. And thats why we ended up with semantically meaningless markup like <p class="tagline">. HTML5 pro vides a so lutio n fo r this: the <hgroup> element. The <hgroup> element acts as a wrapper fo r two o r mo re related heading elements. What do es related mean? It means that, taken to gether, they o nly create a single no de in the do cument o utline. Given this markup: <header> <hgroup> <h1>My Weblog</h1> <h2>A lot of effort went into making this effortless.</h2> </hgroup> </header> <div class="entry"> <h2>Travel day</h2> </div> <div class="entry"> <h2>I'm going to Prague!</h2> </div> This is the do cument o utline that is created: My Weblog (h1 of its hgroup) | +--Travel day (h2) | +--I'm going to Prague! (h2) Yo u can test yo ur o wn pages in the HTML5 Outliner to ensure that yo ure using the heading elements pro perly.
http://diveintohtml5.info/semantics.html#nav-element 16 / 72

Semantics - Dive Into HTML5

7/2/13

ARTICLES
Co ntinuing with o ur example page, lets see what we can do abo ut this markup: <div class="entry"> <p class="post-date">October 22, 2009</p> <h2> <a href="#" rel="bookmark" title="link to this post"> Travel day </a> </h2> </div> Again, this is valid HTML5. But HTML5 pro vides a mo re specific element fo r the co mmo n case o f marking up an article o n a page the aptly named <article> element. <article> <p class="post-date">October 22, 2009</p> <h2> <a href="#" rel="bookmark" title="link to this post"> Travel day </a> </h2> </article> Ah, but its no t quite that simple. There is o ne mo re change yo u sho uld make. Ill sho w it to yo u first, then explain it: <article> <header> <p class="post-date">October 22, 2009</p> <h1> <a href="#" rel="bookmark" title="link to this post"> Travel day </a> </h1> </header> </article> Did yo u catch that? I changed the <h2> element to an <h1>, and wrapped it inside a <header> element. Yo uve already seen the <header> element in actio n. Its purpo se is to wrap all the elements that fo rm the articles header (in this case, the articles publicatio n date and title). Butbutbut sho uldnt yo u o nly have o ne <h1> per do cument? Wo nt this screw up the do cument o utline? No , but to understand why no t, we need to back up a step. In HTML 4, the only way to create a do cument o utline was with the <h1> <h6> elements. If yo u o nly wanted o ne ro o t no de
http://diveintohtml5.info/semantics.html#nav-element 17 / 72

Semantics - Dive Into HTML5

7/2/13

in yo ur o utline, yo u had to limit yo urself to o ne <h1> in yo ur markup. But the HTML5 specificatio n defines an algo rithm fo r generating a do cument o utline that inco rpo rates the new semantic elements in HTML5. The HTML5 algo rithm says that an <article> element creates a new sectio n, that is, a new no de in the do cument o utline. And in HTML5, each sectio n can have its o wn <h1> element. This is a drastic change fro m HTML 4, and heres why its a go o d thing. Many web pages are really generated by templates. A bit o f co ntent is taken fro m o ne so urce and inserted into the page up here; a bit o f co ntent is taken fro m ano ther so urce and inserted into the page do wn there. Many tuto rials are structured the same way. Heres so me HTML markup. Just co py it and paste it into yo ur page. Thats fine fo r small bits o f co ntent, but what if the markup yo ure pasting is an entire sectio n? In that case, the tuto rial will read so mething like this: Heres so me HTML markup. Just co py it, paste it into a text edito r, and fix the heading tags so they match the nesting level o f the co rrespo nding heading tags in the page yo ure pasting it into . Let me put it ano ther way. HTML 4 has no generic heading element. It has six strictly numbered heading elements, <h1> <h6>, which must be nested in exactly that o rder. That kind o f sucks, especially if yo ur page is assembled instead o f autho red. And this is the pro blem that HTML5 so lves with the new sectio ning elements and the new rules fo r the existing heading elements. If yo ure using the new sectio ning elements, I can give yo u this markup: <article> <header> <h1>A syndicated post</h1> </header> <p>Lorem ipsum blah blah</p> </article> and yo u can co py it and paste it anywhere in your page witho ut mo dificatio n. The fact that it co ntains an <h1> element is no t a pro blem, because the entire thing is co ntained within an <article>. The <article> element defines a selfco ntained no de in the do cument o utline, the <h1> element pro vides the title fo r that o utline no de, and all the o ther sectio ning elements o n the page will remain at whatever nesting level they were at befo re.

PRO FESSO R MARKUP SAYS

As with all things o n the web, reality is a little mo re co mplicated than Im letting o n. The new explicit sectio ning elements (like <h1> wrapped in <article>) may interact in unexpected ways with the o ld implicit sectio ning elements (<h1> <h6> by themselves). Yo ur life will be simpler if yo u use o ne o r the o ther, but no t bo th. If yo u must use bo th o n the same page, be sure to check the result in the HTML5 Outliner and verify that yo ur do cument o utline makes sense.

DATES AND TIMES


This is exciting, right? I mean, its no t skiing do wn Mo unt Everest naked while reciting the Star Spangled Banner backwards exciting, but its pretty exciting as far as semantic markup go es. Lets co ntinue with o ur example page. The next line I want to highlight is this o ne: <div class="entry"> <p class="post-date">October 22, 2009</p> <h2>Travel day</h2> </div> Same o ld sto ry, right? A co mmo n pattern designating the publicatio n date o f an article that has no semantic markup to back it up, so autho rs reso rt to generic markup with custo m class attributes. Again, this is valid HTML5. Yo ure no t
http://diveintohtml5.info/semantics.html#nav-element 18 / 72

Semantics - Dive Into HTML5

7/2/13

required to change it. But HTML5 do es pro vide a specific so lutio n fo r this case: the <time> element. <time datetime="2009-10-22" pubdate>October 22, 2009</time> There are three parts to a <time> element: 1. A machine-readable timestamp 2. Human-readable text co ntent 3. An o ptio nal pubdate flag In this example, the datetime attribute o nly specifies a date, no t a time. The fo rmat is a fo ur-digit year, two -digit mo nth, and two -digit day, separated by dashes: <time datetime="2009-10-22" pubdate>October 22, 2009</time> If yo u want to include a time to o , add the letter T after the date, then the time in 24-ho ur fo rmat, then a timezo ne o ffset. <time datetime="2009-10-22T13:59:47-04:00" pubdate> October 22, 2009 1:59pm EDT </time> (The date/time fo rmat is pretty flexible. The HTML5 specificatio n co ntains examples o f valid date/time strings.) No tice I changed the text co ntent the stuff between <time> and </time> to match the machine-readable timestamp. This is no t actually required. The text co ntent can be anything yo u like, as lo ng as yo u pro vide a machine-readable date/timestamp in the datetime attribute. So this is valid HTML5: <time datetime="2009-10-22">last Thursday</time> And this is also valid HTML5: <time datetime="2009-10-22"></time> The final piece o f the puzzle here is the pubdate attribute. Its a Bo o lean attribute, so just add it if yo u need it, like this: <time datetime="2009-10-22" pubdate>October 22, 2009</time> If yo u dislike naked attributes, this is also equivalent: <time datetime="2009-10-22" pubdate="pubdate">October 22, 2009</time> What do es the pubdate attribute mean? It means o ne o f two things. If the <time> element is in an <article> element, it means that this timestamp is the publicatio n date o f the article. If the <time> element is no t in an <article> element, it means that this timestamp is the publicatio n date o f the entire do cument. Heres the entire article, refo rmulated to take full advantage o f HTML5: <article> <header> <time datetime="2009-10-22" pubdate> October 22, 2009 </time>
http://diveintohtml5.info/semantics.html#nav-element 19 / 72

Semantics - Dive Into HTML5

7/2/13

<h1> <a href="#" rel="bookmark" title="link to this post"> Travel day </a> </h1> </header> <p>Lorem ipsum dolor sit amet</p> </article>

NAVIGATION
One o f the mo st impo rtant parts o f any web site is the navigatio n bar. CNN.co m has tabs alo ng the to p o f each page that link to the different news sectio ns Tech, Health, Spo rts, & c. Go o gle search results pages have a similar strip at the to p o f the page to try yo ur search in different Go o gle services Images, Video , Maps, & c. And o ur example page has a navigatio n bar in the header that includes links to different sectio ns o f o ur hypo thetical site ho me, blo g, gallery, and abo ut. This is ho w the navigatio n bar was o riginally marked up: <div id="nav"> <ul> <li><a href="#">home</a></li> <li><a href="#">blog</a></li> <li><a href="#">gallery</a></li> <li><a href="#">about</a></li> </ul> </div> Again, this is valid HTML5. But while its marked up as a list o f fo ur items, there is no thing abo ut the list that tells yo u that its part o f the site navigatio n. Visually, yo u co uld guess that by the fact that its part o f the page header, and by reading the text o f the links. But semantically, there is no thing to distinguish this list o f links fro m any o ther. Who cares abo ut the semantics o f site navigatio n? Fo r o ne, peo ple with disabilities. Why is that? Co nsider this scenario : yo ur mo tio n is limited, and using a mo use is difficult o r impo ssible. To co mpensate, yo u might use a bro wser add-o n that allo ws yo u to jump to (o r jump past) majo r navigatio n links. Or co nsider this: if yo ur sight is limited, yo u might use a dedicated pro gram called a screenreader that uses text-to -speech to speak and summarize web pages. Once yo u get past the page title, the next impo rtant pieces o f info rmatio n abo ut a page are the majo r navigatio n links. If yo u want to navigate quickly, yo ull tell yo ur screenreader to jump to the navigatio n bar and start reading. If yo u want to bro wse quickly, yo u might tell yo ur screenreader to jump over the navigatio n bar and start reading the main co ntent. Either way, being able to determine navigatio n links pro grammatically is impo rtant. So , while theres no thing wro ng with using <div id="nav"> to mark up yo ur site navigatio n, theres no thing particularly right abo ut it either. Its subo ptimal in ways that affect real peo ple. HTML5 pro vides a semantic way to mark up navigatio n sectio ns: the <nav> element. <nav> <ul> <li><a href="#">home</a></li> <li><a href="#">blog</a></li> <li><a href="#">gallery</a></li> <li><a href="#">about</a></li> </ul>
http://diveintohtml5.info/semantics.html#nav-element 20 / 72

Semantics - Dive Into HTML5

7/2/13

</nav>

ASK PRO FESSO R MARKUP

Q: Are skip links co mpatible with the <nav> element? Do I still need skip links in HTML5? A: Skip links allo w readers to skip o ver navigatio n sectio ns. They are helpful fo r disabled users who use third-party so ftware to read a web page alo ud and navigate it witho ut a mo use. (Learn ho w and why to pro vide skip links.) Once screenreaders are updated to reco gnize the <nav> element, skip links will beco me o bso lete, since the screenreader so ftware will be able to auto matically o ffer to skip o ver a navigatio n sectio n marked up with the <nav> element. Ho wever, it will be a while befo re all the disabled users o n the web upgrade to HTML5-savvy screenreader so ftware, so yo u sho uld co ntinue to pro vide yo ur o wn skip links to jump o ver <nav> sectio ns.

FOOTERS
At lo ng last, we have arrived at the end o f o ur example page. The last thing I want to talk abo ut is the last thing o n the page: the fo o ter. The fo o ter was o riginally marked up like this: <div id="footer"> <p>&#167;</p> <p>&#169; 2001&#8211;9 <a href="#">Mark Pilgrim</a></p> </div> This is valid HTML5. If yo u like it, yo u can keep it. But HTML5 pro vides a mo re specific element fo r this: the <footer> element. <footer> <p>&#167;</p> <p>&#169; 2001&#8211;9 <a href="#">Mark Pilgrim</a></p> </footer> Whats appro priate to put in a <footer> element? Pro bably whatever yo ure putting in a <div id="footer"> no w. OK, thats a circular answer. But really, thats it. The HTML5 specificatio n says, A fo o ter typically co ntains info rmatio n abo ut its sectio n such as who wro te it, links to related do cuments, co pyright data, and the like. Thats whats in this example page: a sho rt co pyright statement and a link to an abo ut-the-autho r page. Lo o king aro und at so me po pular sites, I see lo ts o f fo o ter po tential. CNN has a fo o ter that co ntains a co pyright statement, links to translatio ns, and links to terms o f service, privacy, abo ut us, co ntact us, and help pages. All to tally appro priate <footer> material. Go o gle has a famo usly sparse ho me page, but at the bo tto m o f it are links to Advertising Pro grams, Business So lutio ns, and Abo ut Go o gle; a co pyright statement; and a link to Go o gles privacy po licy. All o f that co uld be wrapped in a <footer>. My weblo g has a fo o ter with links to my o ther sites, plus a co pyright statement. Definitely appro priate fo r a <footer> element. (No te that the links themselves sho uld not be wrapped in a <nav> element, because they are no t site navigatio n links; they are just a co llectio n o f links to my o ther pro jects o n o ther sites.) Fat fo o ters are all the rage these days. Take a lo o k at the fo o ter o n the W3C site. It co ntains three co lumns, labeled Navigatio n, Co ntact W3C, and W3C Updates. The markup lo o ks like this, mo re o r less: <div id="w3c_footer">
http://diveintohtml5.info/semantics.html#nav-element 21 / 72

Semantics - Dive Into HTML5

7/2/13

<div class="w3c_footer-nav"> <h3>Navigation</h3> <ul> <li><a href="/">Home</a></li> <li><a href="/standards/">Standards</a></li> <li><a href="/participate/">Participate</a></li> <li><a href="/Consortium/membership">Membership</a></li> <li><a href="/Consortium/">About W3C</a></li> </ul> </div> <div class="w3c_footer-nav"> <h3>Contact W3C</h3> <ul> <li><a href="/Consortium/contact">Contact</a></li> <li><a href="/Help/">Help and FAQ</a></li> <li><a href="/Consortium/sup">Donate</a></li> <li><a href="/Consortium/siteindex">Site Map</a></li> </ul> </div> <div class="w3c_footer-nav"> <h3>W3C Updates</h3> <ul> <li><a href="http://twitter.com/W3C">Twitter</a></li> <li><a href="http://identi.ca/w3c">Identi.ca</a></li> </ul> </div> <p class="copyright">Copyright 2009 W3C</p> </div> To co nvert this to semantic HTML5, I wo uld make the fo llo wing changes: Co nvert the o uter <div id="w3c_footer"> to a <footer> element. Co nvert the first two instances o f <div class="w3c_footer-nav"> to <nav> elements, and the third instance to a <section> element. Co nvert the <h3> headers to <h1>, since theyll no w each be inside a sectio ning element. The <nav> element creates a sectio n in the do cument o utline, just like the <article> element. The final markup might lo o k so mething like this: <footer> <nav> <h1>Navigation</h1> <ul> <li><a href="/">Home</a></li> <li><a href="/standards/">Standards</a></li> <li><a href="/participate/">Participate</a></li> <li><a href="/Consortium/membership">Membership</a></li> <li><a href="/Consortium/">About W3C</a></li> </ul> </nav> <nav> <h1>Contact W3C</h1> <ul> <li><a href="/Consortium/contact">Contact</a></li> <li><a href="/Help/">Help and FAQ</a></li>
http://diveintohtml5.info/semantics.html#nav-element 22 / 72

Semantics - Dive Into HTML5

7/2/13

<li><a href="/Consortium/sup">Donate</a></li> <li><a href="/Consortium/siteindex">Site Map</a></li> </ul> </nav> <section> <h1>W3C Updates</h1> <ul> <li><a href="http://twitter.com/W3C">Twitter</a></li> <li><a href="http://identi.ca/w3c">Identi.ca</a></li> </ul> </section> <p class="copyright">Copyright 2009 W3C</p> </footer>

FURTHER READING
Example pages used thro ugho ut this chapter: Original (HTML 4) Mo dified (HTML5) On character enco ding: The Abso lute Minimum Every So ftware Develo per Abso lutely, Po sitively Must Kno w Abo ut Unico de and Character Sets (No Excuses!) by Jo el Spo lsky On the Go o dness o f Unico de, On Character Strings, and Characters vs. Bytes by Tim Bray On enabling new HTML5 in Internet Explo rer: Ho w to style unkno wn elements in IE by Sjo erd Visscher HTML5 shiv by Jo hn Resig HTML5 enabling script by Remy Sharp The Sto ry o f the HTML5 Shiv by Paul Irish On standards mo des and do ctype sniffing: Activating Bro wser Mo des with Do ctype by Henri Sivo nen. This is the o nly article yo u sho uld read o n the subject. Any article o n do ctypes that do esnt reference Henris wo rk is guaranteed to be o ut o f date, inco mplete, o r wro ng. HTML5-aware validato r: html5.validato r.nu This has been What Do es It All Mean? The full table o f co ntents has mo re if yo ud like to keep reading.

DID YO U KNO W? In asso ciatio n with Go o gle Press, OReilly is distributing this bo o k in a variety o f fo rmats, including paper, ePub, Mo bi, and DRM-free PDF. The paid editio n is called HTML5: Up & Running, and it is available no w. This chapter is included in the paid editio n. If yo u liked this chapter and want to sho w yo ur appreciatio n, yo u can buy HTML5: Up & Running with this
http://diveintohtml5.info/semantics.html#nav-element 23 / 72

Semantics - Dive Into HTML5

7/2/13

affiliate link o r buy an electro nic editio n directly fro m OReilly. Yo ull get a bo o k, and Ill get a buck. I do no t currently accept direct do natio ns.

Co pyright MMIXMMXI Mark Pilgrim

http://diveintohtml5.info/semantics.html#nav-element

24 / 72

Detecting HTML5 Features - Dive Into HTML5

7/2/13

Yo u are here: Ho me Dive Into HTML5

DETECTING HTML5 FEATURES


sho w table o f co ntents

DIVING IN

o u may well ask: Ho w can I start using HTML5 if o lder bro wsers do nt suppo rt it? But the questio n itself is misleading. HTML5 is no t o ne big thing; it is a co llectio n o f individual features. So yo u cant detect HTML5 suppo rt, because that do esnt make any sense. But yo u can detect suppo rt fo r individual features, like canvas, video , o r geo lo catio n.

DETECTION TECHNIQUES
When yo ur bro wser renders a web page, it co nstructs a Do cument Object Mo del (DOM), a co llectio n o f o bjects that represent the HTML elements o n the page. Every element every <p>, every <div>, every <span> is represented in the DOM by a different o bject. (There are also glo bal o bjects, like window and document, that arent tied to specific elements.) All DOM o bjects share a set o f co mmo n pro perties, but so me o bjects have mo re than o thers. In bro wsers that suppo rt HTML5 features, certain o bjects will have unique pro perties. A quick peek at the DOM will tell yo u which features are suppo rted. There are fo ur basic techniques fo r detecting whether a bro wser suppo rts a particular feature. Fro m simplest to mo st co mplex: 1. Check if a certain pro perty exists o n a glo bal o bject (such as window o r navigator). Example: testing fo r geo lo catio n suppo rt 2. Create an element, then check if a certain pro perty exists o n that element. Example: testing fo r canvas suppo rt 3. Create an element, check if a certain metho d exists o n that element, then call the metho d and check the value it returns. Example: testing which video fo rmats are suppo rted 4. Create an element, set a pro perty to a certain value, then check if the pro perty has retained its value. Example: testing which <input> types are suppo rted

MODERNIZR, AN HTML5 DETECTION LIBRARY


Mo dernizr is an o pen so urce, MIT-licensed JavaScript library that detects suppo rt fo r many HTML5 & CSS3 features. Yo u sho uld always use the latest versio n. To use it, include the fo llo wing <script> element at the to p o f yo ur page. <!DOCTYPE html>

http://diveintohtml5.info/detect.html#divingin

25 / 72

<!DOCTYPE html>- Dive Into HTML5 Detecting HTML5 Features <html> <head> <meta charset="utf-8"> <title>Dive Into HTML5</title> <script src="modernizr.min.js"></script> </head> <body> ... </body> </html>

7/2/13

It goes to your <head>


Mo dernizr runs auto matically. There is no modernizr_init() functio n to call. When it runs, it creates a glo bal o bject called Modernizr, that co ntains a set o f Bo o lean pro perties fo r each feature it can detect. Fo r example, if yo ur bro wser suppo rts the canvas API, the Modernizr.canvas pro perty will be true. If yo ur bro wser do es no t suppo rt the canvas API, the Modernizr.canvas pro perty will be false. if (Modernizr.canvas) { // let's draw some shapes! } else { // no native canvas support available :( }

CANVAS
HTML5 defines the <canvas> element as a reso lutio ndependent bitmap canvas that can be used fo r rendering graphs, game graphics, o r o ther visual images o n the fly. A canvas is a rectangle in yo ur page where yo u can use JavaScript to draw anything yo u want. HTML5 defines a set o f functio ns (the canvas API) fo r drawing shapes, defining paths, creating gradients, and applying transfo rmatio ns. Checking fo r the canvas API uses detectio n technique #2. If yo ur bro wser suppo rts the canvas API, the DOM o bject it creates to represent a <canvas> element will have a getContext() metho d. If yo ur bro wser do esnt suppo rt the canvas API, the DOM o bject it creates fo r a <canvas> element will o nly have the set o f co mmo n pro perties, but no t anything canvas-specific. function supports_canvas() { return !!document.createElement('canvas').getContext; } This functio n starts by creating a dummy <canvas> element. But the element is never attached to yo ur page, so no o ne will ever see it. Its just flo ating in memo ry, go ing no where and do ing no thing, like a cano e o n a lazy river. return !!document.createElement('canvas').getContext; As so o n as yo u create the dummy <canvas> element, yo u test fo r the presence o f a getContext() metho d. This metho d will o nly exist if yo ur bro wser suppo rts the canvas API. return !!document.createElement('canvas').getContext; Finally, yo u use the do uble-negative trick to fo rce the result to a Bo o lean value (true o r false).

Yo ur bro wser suppo rts the canvas API.

http://diveintohtml5.info/detect.html#divingin

26 / 72

Detecting HTML5 Features - Dive Into HTML5

7/2/13

return !!document.createElement('canvas').getContext; This functio n will detect suppo rt fo r mo st o f the canvas API, including shapes, paths, gradients & patterns. It will no t detect the third-party explorercanvas library that implements the canvas API in Micro so ft Internet Explo rer. Instead o f writing this functio n yo urself, yo u can use Mo dernizr to detect suppo rt fo r the canvas API.

check for canvas support


if (Modernizr.canvas) { // let's draw some shapes! } else { // no native canvas support available :( } There is a separate test fo r the canvas text API, which I will demo nstrate next.

CANVAS TEXT
Even if yo ur bro wser suppo rts the canvas API, it might no t suppo rt the canvas text API. The canvas API grew o ver time, and the text functio ns were added late in the game. So me bro wsers shipped with canvas suppo rt befo re the text API was co mplete. Checking fo r the canvas text API uses detectio n technique #2. If yo ur bro wser suppo rts the canvas API, the DOM o bject it creates to represent a <canvas> element will have the getContext() metho d. If yo ur bro wser do esnt suppo rt the canvas API, the DOM o bject it creates fo r a <canvas> element will o nly have the set o f co mmo n pro perties, but no t anything canvas-specific. function supports_canvas_text() { if (!supports_canvas()) { return false; } var dummy_canvas = document.createElement('canvas'); var context = dummy_canvas.getContext('2d'); return typeof context.fillText == 'function'; } The functio n starts by checking fo r canvas suppo rt, using the supports_canvas() functio n yo u just saw in the previo us sectio n. If yo ur bro wser do esnt suppo rt the canvas API, it certainly wo nt suppo rt the canvas text API! if (!supports_canvas()) { return false; } Next, yo u create a dummy <canvas> element and get its drawing co ntext. This is guaranteed to wo rk, because the supports_canvas() functio n already checked that the getContext() metho d exists o n all canvas o bjects. var dummy_canvas = document.createElement('canvas'); var context = dummy_canvas.getContext('2d'); Finally, yo u check whether the drawing co ntext has a fillText() functio n. If it do es, the canvas text API is available. Ho o ray! return typeof context.fillText == 'function';
http://diveintohtml5.info/detect.html#divingin 27 / 72

Yo ur bro wser suppo rts the canvas text API.

Detecting HTML5 Features - Dive Into HTML5

7/2/13

Instead o f writing this functio n yo urself, yo u can use Mo dernizr to detect suppo rt fo r the canvas text API.

check for canvas text support


if (Modernizr.canvastext) { // let's draw some text! } else { // no native canvas text support available :( }

VIDEO
HTML5 defines a new element called <video> fo r embedding video in yo ur web pages. Embedding video used to be impo ssible witho ut third-party plugins such as Apple QuickTime o r Ado be Flash . The <video> element is designed to be usable witho ut any detectio n scripts. Yo u can specify multiple video files, and bro wsers that suppo rt HTML5 video will cho o se o ne based o n what video fo rmats they suppo rt. (See A gentle intro ductio n to video enco ding part 1: co ntainer fo rmats and part 2: lo ssy video co decs to learn abo ut different video fo rmats.) Bro wsers that do nt suppo rt HTML5 video will igno re the <video> element co mpletely, but yo u can use this to yo ur advantage and tell them to play video thro ugh a third-party plugin instead. Kro c Camen has designed a so lutio n called Video fo r Everybo dy! that uses HTML5 video where available, but falls back to QuickTime o r Flash in o lder bro wsers. This so lutio n uses no JavaScript whatso ever, and it wo rks in virtually every bro wser, including mo bile bro wsers. If yo u want to do mo re with video than plo p it o n yo ur page and play it, yo ull need to use JavaScript. Checking fo r video suppo rt uses detectio n technique #2. If yo ur bro wser suppo rts HTML5 video , the DOM o bject it creates to represent a <video> element will have a canPlayType() metho d. If yo ur bro wser do esnt suppo rt HTML5 video , the DOM o bject it creates fo r a <video> element will have o nly the set o f pro perties co mmo n to all elements. Yo u can check fo r video suppo rt using this functio n: function supports_video() { return !!document.createElement('video').canPlayType; } Instead o f writing this functio n yo urself, yo u can use Mo dernizr to detect suppo rt fo r HTML5 video . Yo ur bro wser suppo rts HTML5 video .

check for HTML5 video support


if (Modernizr.video) { // let's play some video! } else { // no native video support available :( // maybe check for QuickTime or Flash instead } In the Video chapter, Ill explain ano ther so lutio n that uses these detectio n techniques to co nvert <video> elements to Flash-based video players, fo r the benefit o f bro wsers that do nt suppo rt HTML5 video . There is a separate test fo r detecting which video fo rmats yo ur bro wser can play, which I will demo nstrate next.

VIDEO FORMATS
http://diveintohtml5.info/detect.html#divingin 28 / 72

Detecting HTML5 Features - Dive Into HTML5

7/2/13

Video fo rmats are like written languages. An English newspaper may co nvey the same info rmatio n as a Spanish newspaper, but if yo u can o nly read English, o nly o ne o f them will be useful to yo u! To play a video , yo ur bro wser needs to understand the language in which the video was written. The language o f a video is called a co dec this is the algo rithm used to enco de the video into a stream o f bits. There are do zens o f co decs in use all o ver the wo rld. Which o ne sho uld yo u use? The unfo rtunate reality o f HTML5 video is that bro wsers cant agree o n a

Yo ur bro wser can play Ogg Theo ra video , but no t H.264 video . Hey, yo u can play WebM video , to o !

single co dec. Ho wever, they seem to have narro wed it do wn to two . One co dec co sts mo ney (because o f patent licensing), but it wo rks in Safari and o n the iPho ne. (This o ne also wo rks in Flash if yo u use a so lutio n like Video fo r Everybo dy!) The o ther co dec is free and wo rks in o pen so urce bro wsers like Chro mium and Mo zilla Firefo x. Checking fo r video fo rmat suppo rt uses detectio n technique #3. If yo ur bro wser suppo rts HTML5 video , the DOM o bject it creates to represent a <video> element will have a canPlayType() metho d. This metho d will tell yo u whether the bro wser suppo rts a particular video fo rmat. This functio n checks fo r the patent-encumbered fo rmat suppo rted by Macs and iPho nes. function supports_h264_baseline_video() { if (!supports_video()) { return false; } var v = document.createElement("video"); return v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"'); } The functio n starts by checking fo r HTML5 video suppo rt, using the supports_video() functio n yo u just saw in the previo us sectio n. If yo ur bro wser do esnt suppo rt HTML5 video , it certainly wo nt suppo rt any video fo rmats! if (!supports_video()) { return false; } Then the functio n creates a dummy <video> element (but do esnt attach it to the page, so it wo nt be visible) and calls the canPlayType() metho d. This metho d is guaranteed to be there, because the supports_video() functio n just checked fo r it. var v = document.createElement("video"); A video fo rmat is really a co mbinatio n o f different things. In technical terms, yo ure asking the bro wser whether it can play H.264 Baseline video and AAC LC audio in an MPEG-4 co ntainer. (Ill explain what all that means in the Video chapter. Yo u might also be interested in reading A gentle intro ductio n to video enco ding .) return v.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"'); The canPlayType() functio n do esnt return true o r false. In reco gnitio n o f ho w co mplex video fo rmats are, the functio n returns a string: "probably" if the bro wser is fairly co nfident it can play this fo rmat "maybe" if the bro wser thinks it might be able to play this fo rmat "" (an empty string) if the bro wser is certain it cant play this fo rmat This seco nd functio n checks fo r the o pen video fo rmat suppo rted by Mo zilla Firefo x and o ther o pen so urce bro wsers. The pro cess is exactly the same; the o nly difference is the string yo u pass in to the canPlayType() functio n. In technical terms, yo ure asking the bro wser whether it can play Theo ra video and Vo rbis audio in an Ogg co ntainer.
http://diveintohtml5.info/detect.html#divingin 29 / 72

Detecting HTML5 Features - Dive Into HTML5

7/2/13

function supports_ogg_theora_video() { if (!supports_video()) { return false; } var v = document.createElement("video"); return v.canPlayType('video/ogg; codecs="theora, vorbis"'); } Finally, WebM is a newly o pen-so urced (and no n-patent-encumbered) video co dec that will be included in the next versio n o f majo r bro wsers, including Chro me, Firefo x, and Opera. Yo u can use the same technique to detect suppo rt fo r o pen WebM video . function supports_webm_video() { if (!supports_video()) { return false; } var v = document.createElement("video"); return v.canPlayType('video/webm; codecs="vp8, vorbis"'); } Instead o f writing this functio n yo urself, yo u can use Mo dernizr (1.5 o r later) to detect suppo rt fo r different HTML5 video fo rmats.

check for HTML5 video formats


if (Modernizr.video) { // let's play some video! but what kind? if (Modernizr.video.webm) { // try WebM } else if (Modernizr.video.ogg) { // try Ogg Theora + Vorbis in an Ogg container } else if (Modernizr.video.h264){ // try H.264 video + AAC audio in an MP4 container } }

LOCAL STORAGE
HTML5 sto rage pro vides a way fo r web sites to sto re info rmatio n o n yo ur co mputer and retrieve it later. The co ncept is similar to co o kies, but its designed fo r larger quantities o f info rmatio n. Co o kies are limited in size, and yo ur bro wser sends them back to the web server every time it requests a new page (which takes extra time and precio us bandwidth). HTML5 sto rage stays o n yo ur co mputer, and web sites can access it with JavaScript after the page is lo aded.

Yo ur bro wser suppo rts HTML5 sto rage.

ASK PRO FESSO R MARKUP

Q: Is lo cal sto rage really part o f HTML5? Why is it in a separate specificatio n? A: The sho rt answer is yes, lo cal sto rage is part o f HTML5. The slightly lo nger answer is that lo cal sto rage used to be part o f the main HTML5 specificatio n, but it was split o ut into a separate specificatio n because so me peo ple in the HTML5 Wo rking Gro up co mplained that HTML5 was to o big. If that so unds like slicing a pie into mo re pieces to reduce the to tal number o f calo ries well, welco me to the wacky wo rld o f standards.

Checking fo r HTML5 sto rage suppo rt uses detectio n technique #1. If yo ur bro wser suppo rts HTML5 sto rage, there will be a localStorage pro perty o n the glo bal window o bject. If yo ur bro wser do esnt suppo rt HTML5 sto rage, the localStorage pro perty will be undefined. Due to an unfo rtunate bug in o lder versio ns o f Firefo x, this test will raise an exceptio n if
http://diveintohtml5.info/detect.html#divingin 30 / 72

Detecting HTML5 Features - Dive Into HTML5

7/2/13

co o kies are disabled, so the entire test is wrapped in a try..catch statement. function supports_local_storage() { try { return 'localStorage' in window && window['localStorage'] !== null; } catch(e){ return false; } } Instead o f writing this functio n yo urself, yo u can use Mo dernizr (1.1 o r later) to detect suppo rt fo r HTML5 lo cal sto rage.

check for HTML5 local storage


if (Modernizr.localstorage) { // window.localStorage is available! } else { // no native support for local storage :( // try a fallback or another third-party solution } No te that JavaScript is case-sensitive. The Mo dernizr attribute is called localstorage (all lo wercase), but the DOM pro perty is called window.localStorage (mixed case).

ASK PRO FESSO R MARKUP

Q: Ho w secure is my HTML5 sto rage database? Can anyo ne read it? A: Anyo ne who has physical access to yo ur co mputer can pro bably lo o k at (o r even change) yo ur HTML5 sto rage database. Within yo ur bro wser, any web site can read and mo dify its o wn values, but sites cant access values sto red by o ther sites. This is called a same-o rigin restrictio n.

WEB WORKERS
Web Wo rkers pro vide a standard way fo r bro wsers to run JavaScript in the backgro und. With web wo rkers, yo u can spawn multiple threads that all Yo ur bro wser suppo rts web wo rkers. run at the same time, mo re o r less. (Think o f ho w yo ur co mputer can run multiple applicatio ns at the same time, and yo ure mo st o f the way there.) These backgro und threads can do co mplex mathematical calculatio ns, make netwo rk requests, o r access lo cal sto rage while the main web page respo nds to the user scro lling, clicking, o r typing. Checking fo r web wo rkers uses detectio n technique #1. If yo ur bro wser suppo rts the Web Wo rker API, there will be a Worker pro perty o n the glo bal window o bject. If yo ur bro wser do esnt suppo rt the Web Wo rker API, the Worker pro perty will be undefined. function supports_web_workers() { return !!window.Worker; } Instead o f writing this functio n yo urself, yo u can use Mo dernizr (1.1 o r later) to detect suppo rt fo r web wo rkers.

http://diveintohtml5.info/detect.html#divingin

31 / 72

Detecting HTML5 Features - Dive Into HTML5

7/2/13

check for web workers


if (Modernizr.webworkers) { // window.Worker is available! } else { // no native support for web workers :( // try a fallback or another third-party solution } No te that JavaScript is case-sensitive. The Mo dernizr attribute is called webworkers (all lo wercase), but the DOM o bject is called window.Worker (with a capital W in Wo rker).

OFFLINE WEB APPLICATIONS


Reading static web pages o ffline is easy: co nnect to the Internet, lo ad a web page, disco nnect fro m the Internet, drive to a secluded cabin, and read the web page at yo ur leisure. (To save time, yo u may wish to skip the step abo ut the cabin.) But what abo ut web applicatio ns like Gmail o r Go o gle Do cs? Thanks to HTML5, anyo ne (no t just Go o gle!) can build a web applicatio n that wo rks o ffline. Offline web applicatio ns start o ut as o nline web applicatio ns. The first time yo u visit an o ffline-enabled web site, the web server tells yo ur bro wser which files it needs in o rder to wo rk o ffline. These files can be anything HTML, JavaScript, images, even video s. Once yo ur bro wser do wnlo ads all the necessary files, yo u can revisit the web site even if yo ure no t co nnected to the Internet. Yo ur bro wser will no tice that yo ure o ffline and use the files it has already do wnlo aded. When yo u get back o nline, any changes yo uve made can be uplo aded to the remo te web server. Checking fo r o ffline suppo rt uses detectio n technique #1. If yo ur bro wser suppo rts o ffline web applicatio ns, there will be an applicationCache pro perty o n the glo bal window o bject. If yo ur bro wser do esnt suppo rt o ffline web applicatio ns, the applicationCache pro perty will be undefined. Yo u can check fo r o ffline suppo rt with the fo llo wing functio n: function supports_offline() { return !!window.applicationCache; } Instead o f writing this functio n yo urself, yo u can use Mo dernizr (1.1 o r later) to detect suppo rt fo r o ffline web applicatio ns.

Yo ur bro wser suppo rts o ffline web applicatio ns.

check for offline support


if (Modernizr.applicationcache) { // window.applicationCache is available! } else { // no native support for offline :( // try a fallback or another third-party solution } No te that JavaScript is case-sensitive. The Mo dernizr attribute is called applicationcache (all lo wercase), but the DOM o bject is called window.applicationCache (mixed case).

GEOLOCATION
Geo lo catio n is the art o f figuring o ut where yo u are in the wo rld and (o ptio nally) sharing that info rmatio n with peo ple yo u trust. There is mo re than o ne way to figure o ut where yo u are yo ur IP address, yo ur wireless netwo rk co nnectio n, which
http://diveintohtml5.info/detect.html#divingin 32 / 72

Detecting HTML5 Features - Dive Into HTML5

7/2/13

cell to wer yo ur pho ne is talking to , o r dedicated GPS hardware that calculates latitude and lo ngitude fro m info rmatio n sent by satellites in the sky.

ASK PRO FESSO R MARKUP

Q: Is geo lo catio n part o f HTML5? Why are yo u talking abo ut it? A: Geo lo catio n suppo rt is being added to bro wsers right no w, alo ng with suppo rt fo r new HTML5 features. Strictly speaking, geo lo catio n is being standardized by the Geo lo catio n Wo rking Gro up, which is separate fro m the HTML5 Wo rking Gro up. But Im go ing to talk abo ut geo lo catio n in this bo o k anyway, because its part o f the evo lutio n o f the web thats happening no w.

Checking fo r geo lo catio n suppo rt uses detectio n technique #1. If yo ur bro wser suppo rts the geo lo catio n API, there will be a geolocation pro perty o n the glo bal navigator o bject. If yo ur bro wser do esnt suppo rt the geo lo catio n API, the geolocation pro perty will no t be present inside o f navigator. Heres ho w to check fo r geo lo catio n suppo rt: function supports_geolocation() { return 'geolocation' in navigator; } Instead o f writing this functio n yo urself, yo u can use Mo dernizr to detect suppo rt fo r the geo lo catio n API.

check for geolocation support


if (Modernizr.geolocation) { // let's find out where you are! } else { // no native geolocation support available :( // try geoPosition.js or another third-party solution } If yo ur bro wser do es no t suppo rt the geo lo catio n API natively, there is still ho pe. Geo Po sitio n.js is a JavaScript library that aims to pro vide Geo lo catio n suppo rt in o lder bro wsers like Blackberry, Palm OS, and Micro so ft Internet Explo rer 6, 7, and 8. Its no t quite the same as the navigator.geolocation API, but it serves the same purpo se.

http://diveintohtml5.info/detect.html#divingin

33 / 72

Detecting HTML5 Features - Dive Into HTML5

7/2/13

There are also device-specific geo lo catio n APIs o n o lder mo bile pho ne platfo rms, including BlackBerry, No kia, Palm, and OMTP BONDI. The chapter o n geo lo catio n will go into excruciating detail abo ut ho w to use all o f these different APIs.

INPUT TYPES
Yo u kno w all abo ut web fo rms, right? Make a <form>, add a few <input type="text"> elements and maybe an <input type="password">, and finish it o ff with an <input type="submit"> butto n. Yo u do nt kno w the half o f it. HTML5 defines o ver a do zen new input types that yo u can use in yo ur fo rms. 1. <input type="search"> fo r search bo xes 2. <input type="number"> fo r spinbo xes 3. <input type="range"> fo r sliders 4. <input type="color"> fo r co lo r pickers 5. <input type="tel"> fo r telepho ne numbers 6. <input type="url"> fo r web addresses 7. <input type="email"> fo r email addresses 8. <input type="date"> fo r calendar date pickers 9. <input type="month"> fo r mo nths 10. <input type="week"> fo r weeks 11. <input type="time"> fo r timestamps 12. <input type="datetime"> fo r precise, abso lute date+time stamps 13. <input type="datetime-local"> fo r lo cal dates and times Checking fo r HTML5 input types uses detectio n technique #4. First, yo u create a dummy <input> element in memo ry. The default input type fo r all <input> elements is "text". This will pro ve to be vitally impo rtant. var i = document.createElement("input"); Next, set the type attribute o n the dummy <input> element to the input type yo u want to detect. i.setAttribute("type", "color"); If yo ur bro wser suppo rts that particular input type, the type pro perty will retain the value yo u set. If yo ur bro wser do esnt suppo rt that particular input type, it will igno re the value yo u set and the type pro perty will still be "text". return i.type !== "text"; Instead o f writing 13 separate functio ns yo urself, yo u can use Mo dernizr to detect suppo rt fo r all the new input types defined in HTML5. Mo dernizr reuses a single <input> element to efficiently detect suppo rt fo r all 13 input types. Then it builds a hash called Modernizr.inputtypes, that co ntains 13 keys (the HTML5 type attributes) and 13 Bo o lean values (true if suppo rted, false if no t).

check for native date picker


if (!Modernizr.inputtypes.date) { // no native support for <input type="date"> :( // maybe build one yourself with Dojo or jQueryUI
http://diveintohtml5.info/detect.html#divingin

34 / 72

Detecting HTML5 Features - Dive Into HTML5

7/2/13

PLACEHOLDER TEXT
Checking fo r placeho lder suppo rt uses detectio n technique #2. If yo ur bro wser suppo rts placeho lder text in input fields, the DOM o bject it creates to represent an <input> element will have a placeholder pro perty (even if yo u do nt include a placeholder attribute in yo ur HTML). If yo ur bro wser do esnt suppo rt placeho lder text, the DOM o bject it creates fo r an <input> element will no t have a placeholder pro perty. function supports_input_placeholder() { var i = document.createElement('input'); return 'placeholder' in i; } Instead o f writing this functio n yo urself, yo u can use Mo dernizr (1.1 o r later) to detect suppo rt fo r placeho lder text.

check for placeholder text


if (Modernizr.input.placeholder) { // your placeholder text should already be visible! } else { // no placeholder support :( // fall back to a scripted solution }

FORM AUTOFOCUS
Web sites can use JavaScript to fo cus the first input field o f a web fo rm auto matically. Fo r example, the ho me page o f Go o gle.co m will auto fo cus the input bo x so yo u can type yo ur search keywo rds witho ut having to po sitio n the curso r in the search bo x. While this is co nvenient fo r mo st peo ple, it can be anno ying fo r po wer users o r peo ple with special needs. If yo u press the space bar expecting to scro ll the page, the page will no t scro ll because the fo cus is already in a fo rm input field. (It types a space in the field instead o f scro lling.) If yo u fo cus a different input field while the page is still lo ading, the sites auto fo cus script may helpfully mo ve the fo cus back to the o riginal input field upo n co mpletio n, disrupting yo ur flo w and causing yo u to type in the wro ng place. Because the auto fo cusing is do ne with JavaScript, it can be tricky to handle all o f these edge cases, and there is little reco urse fo r peo ple who do nt want a web page to steal the fo cus. To so lve this pro blem, HTML5 intro duces an autofocus attribute o n all web fo rm co ntro ls. The autofocus attribute do es exactly what it says o n the tin: it mo ves the fo cus to a particular input field. But because its just markup instead o f a script, the behavio r will be co nsistent acro ss all web sites. Also , bro wser vendo rs (o r extensio n autho rs) can o ffer users a way to disable the auto fo cusing behavio r. Checking fo r auto fo cus suppo rt uses detectio n technique #2. If yo ur bro wser suppo rts auto fo cusing web fo rm co ntro ls, the DOM o bject it creates to represent an <input> element will have an autofocus pro perty (even if yo u do nt include the autofocus attribute in yo ur HTML). If yo ur bro wser do esnt suppo rt auto fo cusing web fo rm co ntro ls, the DOM o bject it creates fo r an <input> element will no t have an autofocus pro perty. Yo u can detect auto fo cus suppo rt with this functio n: function supports_input_autofocus() { var i = document.createElement('input'); return 'autofocus' in i; }
http://diveintohtml5.info/detect.html#divingin 35 / 72

Detecting HTML5 Features - Dive Into HTML5

7/2/13

Instead o f writing this functio n yo urself, yo u can use Mo dernizr (1.1 o r later) to detect suppo rt fo r auto fo cused fo rm fields.

check for autofocus support


if (Modernizr.input.autofocus) { // autofocus works! } else { // no autofocus support :( // fall back to a scripted solution }

MICRODATA
Micro data is a standardized way to pro vide additio nal semantics in yo ur web pages. Fo r example, yo u can use micro data to declare that a pho to graph is available under a specific Creative Co mmo ns license. As yo ull see in the distributed extensibility chapter, yo u can use micro data to mark up an Abo ut Me page. Bro wsers, bro wser extensio ns, and search engines can co nvert yo ur HTML5 micro data markup into a vCard, a standard fo rmat fo r sharing co ntact info rmatio n. Yo u can also define yo ur o wn micro data vo cabularies. The HTML5 micro data standard includes bo th HTML markup (primarily fo r search engines) and a set o f DOM functio ns (primarily fo r bro wsers). Theres no harm in including micro data markup in yo ur web pages. Its no thing mo re than a few well-placed attributes, and search engines that do nt understand the micro data attributes will just igno re them. But if yo u need to access o r manipulate micro data thro ugh the DOM, yo ull need to check whether the bro wser suppo rts the micro data DOM API. Checking fo r HTML5 micro data API suppo rt uses detectio n technique #1. If yo ur bro wser suppo rts the HTML5 micro data API, there will be a getItems() functio n o n the glo bal document o bject. If yo ur bro wser do esnt suppo rt micro data, the getItems() functio n will be undefined. function supports_microdata_api() { return !!document.getItems; } Mo dernizr do es no t yet suppo rt checking fo r the micro data API, so yo ull need to use the functio n like the o ne listed abo ve.

HISTORY API
The HTML5 histo ry API is a standardized way to manipulate the bro wser histo ry via script. Part o f this API navigating the histo ry has been available in previo us versio ns o f HTML. The new part in HTML5 is a way to add entries to the bro wser histo ry, and respo nd when tho se entries are remo ved fro m the stack by the user pressing the bro wsers back butto n. This means that the URL can co ntinue to do its jo b as a unique identifier fo r the current reso urce, even in script-heavy applicatio ns that do nt ever perfo rm a full page refresh. Checking fo r HTML5 histo ry API suppo rt uses detectio n technique #1. If yo ur bro wser suppo rts the HTML5 histo ry API, there will be a pushState() functio n o n the glo bal history o bject. If yo ur bro wser do esnt suppo rt the histo ry API, the pushState() functio n will be undefined. function supports_history_api() { return !!(window.history && history.pushState); }
http://diveintohtml5.info/detect.html#divingin 36 / 72

Detecting HTML5 Features - Dive Into HTML5

7/2/13

Instead o f writing this functio n yo urself, yo u can use Mo dernizr (1.6 o r later) to detect suppo rt fo r the HTML5 histo ry API.

check for history API support


if (Modernizr.history) { // history management works! } else { // no history support :( // fall back to a scripted solution like History.js }

FURTHER READING
Specificatio ns and standards: the <canvas> element the <video> element <input> types the <input placeholder> attribute the <input autofocus> attribute HTML5 sto rage Web Wo rkers Offline web applicatio ns Geo lo catio n API Sessio n histo ry and navigatio n JavaScript libraries: Mo dernizr, an HTML5 detectio n library geo .js, a geo lo catio n API wrapper HTML5 Cro ss-bro wser Po lyfills Other articles and tuto rials: Video fo r Everybo dy! A gentle intro ductio n to video enco ding Video type parameters The All-In-One Almo st-Alphabetical Guide to Detecting Everything Internet Explo rer 9 Guide fo r Develo pers This has been Detecting HTML5 Features. The full table o f co ntents has mo re if yo ud like to keep reading.

DID YO U KNO W? In asso ciatio n with Go o gle Press, OReilly is distributing this bo o k in a variety o f fo rmats, including paper, ePub, Mo bi, and DRM-free PDF. The paid editio n is called HTML5: Up & Running, and it is available no w. This chapter is included in the paid editio n. If yo u liked this chapter and want to sho w yo ur appreciatio n, yo u can buy HTML5: Up & Running with this affiliate link o r buy an electro nic editio n directly fro m OReilly. Yo ull get a bo o k, and Ill get a buck. I do no t currently accept direct do natio ns.

http://diveintohtml5.info/detect.html#divingin

37 / 72

Detecting HTML5 Features - Dive Into HTML5

7/2/13

Co pyright MMIXMMXI Mark Pilgrim

http://diveintohtml5.info/detect.html#divingin

38 / 72

Canvas - Dive Into HTML5

7/2/13

Yo u are here: Ho me Dive Into HTML5

LETS CALL IT A DRAW(ING SURFACE)


sho w table o f co ntents

DIVING IN

H
IE
7.0+*

TML 5 defines the <canvas> element as a reso lutio n-dependent bitmap canvas which can be used fo r rendering graphs, game graphics, o r o ther visual images o n the fly. A canvas is a rectangle in yo ur page where yo u can use JavaScript to draw anything yo u want.

FIREFOX
3.0+

BASIC <CANVAS> SUPPORT SAFARI CHROME OPERA


3.0+ 3.0+ 10.0+

IPHONE
1.0+

ANDROID
1.0+

* Internet Explorer 7 and 8 require the third- party explorercanvas library. Internet Explorer 9 supports <canvas> natively.
So what do es a canvas lo o k like? No thing, really. A <canvas> element has no co ntent and no bo rder o f its o wn.

Invisible canvas
The markup lo o ks like this: <canvas width="300" height="225"></canvas> Lets add a do tted bo rder so we can see what were dealing with.

http://diveintohtml5.info/canvas.html

39 / 72

Canvas - Dive Into HTML5

7/2/13

Canvas with border


Yo u can have mo re than o ne <canvas> element o n the same page. Each canvas will sho w up in the DOM, and each canvas maintains its o wn state. If yo u give each canvas an id attribute, yo u can access them just like any o ther element. Lets expand that markup to include an id attribute: <canvas id="a" width="300" height="225"></canvas> No w yo u can easily find that <canvas> element in the DOM. var a_canvas = document.getElementById("a");

SIMPLE SHAPES
IE
7.0+*

FIREFOX
3.0+

SAFARI
3.0+

CHROME
3.0+

OPERA
10.0+

IPHONE
1.0+

ANDROID
1.0+

* Internet Explorer 7 and 8 require the third- party explorercanvas library. Internet Explorer 9 supports <canvas> shapes natively.
Every canvas starts o ut blank. Thats bo ring! Lets draw so mething.

Click to draw on this canvas


The onclick handler called this functio n: function draw_b() { var b_canvas = document.getElementById("b"); var b_context = b_canvas.getContext("2d"); b_context.fillRect(50, 25, 150, 100); } The 1 S T line o f the functio n is no thing special; it just finds the <canvas> element in the DOM.

And then theres this


function draw_b() { var b_canvas = document.getElementById("b"); var b_context = b_canvas.getContext("2d"); b_context.fillRect(50, 25, 150, 100); } Every canvas has a drawing co ntext, which is where all the fun stuff happens. Once yo uve fo und a <canvas> element in the DOM (by using document.getElementById() o r any o ther metho d yo u like), yo u call its getContext() metho d. Yo u m ust pass the string "2d" to the getContext() metho d.
http://diveintohtml5.info/canvas.html 40 / 72

Canvas - Dive Into HTML5

7/2/13

Q: Is there a 3-D canvas? A: No t yet. Individual vendo rs have experimented with their o wn three-dimensio nal canvas APIs, but no ne o f them have been standardized. The HTML5 specificatio n no tes, A future versio n o f this specificatio n will pro bably define a 3d co ntext. So , yo u have a <canvas> element, and yo u have its drawing co ntext. The drawing co ntext is where all the drawing metho ds and pro perties are defined. Theres a who le gro up o f pro perties and metho ds devo ted to drawing rectangles: The fillStyle pro perty can be a CSS co lo r, a pattern, o r a gradient. (Mo re o n gradients sho rtly.) The default fillStyle is so lid black, but yo u can set it to whatever yo u like. Each drawing co ntext remembers its o wn pro perties as lo ng as the page is o pen, unless yo u do so mething to reset it. fillRect(x, y, width, height) draws a rectangle filled with the current fill style. The strokeStyle pro perty is like fillStyle it can be a CSS co lo r, a pattern, o r a gradient. strokeRect(x, y, width, height) draws an rectangle with the current stro ke style. strokeRect do esnt fill in the middle; it just draws the edges. clearRect(x, y, width, height) clears the pixels in the specified rectangle.

ASK PRO FESSO R MARKUP

Q: Can I reset a canvas? A: Yes. Setting the width o r height o f a <canvas> element will erase its co ntents and reset all the pro perties o f its drawing co ntext to their default values. Yo u do nt even need to change the width; yo u can simply set it to its current value, like this: var b_canvas = document.getElementById("b"); b_canvas.width = b_canvas.width;

Getting back to that co de sample in the previo us example

Draw a rectangle
var b_canvas = document.getElementById("b"); var b_context = b_canvas.getContext("2d"); b_context.fillRect(50, 25, 150, 100); Calling the fillRect() metho d draws the rectangle and fills it with the current fill style, which is black until yo u change it. The rectangle is bo unded by its upper-left co rner (50, 25), its width (150), and its height (100). To get a better picture o f ho w that wo rks, lets lo o k at the canvas co o rdinate system.

CANVAS COORDINATES
The canvas is a two -dimensio nal grid. The co o rdinate (0, 0) is at the upper-left co rner o f the canvas. Alo ng the X-axis, values increase to wards the right edge o f the canvas. Alo ng the Y-axis, values increase to wards the bo tto m edge o f the canvas.

Canvas coordinates diagram

http://diveintohtml5.info/canvas.html

41 / 72

Canvas - Dive Into HTML5

7/2/13

That co o rdinate diagram was drawn with a <canvas> element. It co mprises a set o f o ff-white vertical lines a set o f o ff-white ho rizo ntal lines two black ho rizo ntal lines two small black diago nal lines that fo rm an arro w two black vertical lines two small black diago nal lines that fo rm ano ther arro w the letter x the letter y the text (0, 0) near the upper-left co rner the text (500, 375) near the lo wer-right co rner a do t in the upper-left co rner, and ano ther in the lo wer-right co rner First, we need to define the <canvas> element itself. The <canvas> element defines the width and height, and the id so we can find it later. <canvas id="c" width="500" height="375"></canvas> Then we need a script to find the <canvas> element in the DOM and get its drawing co ntext. var c_canvas = document.getElementById("c"); var context = c_canvas.getContext("2d"); No w we can start drawing lines.

PATHS
IE
7.0+*

FIREFOX
3.0+

SAFARI
3.0+

CHROME
3.0+

OPERA
10.0+

IPHONE
1.0+

ANDROID

1.0+ * Internet Explorer 7 and 8 require the third- party explorercanvas library. Internet Explorer 9 supports <canvas>

paths natively.

http://diveintohtml5.info/canvas.html

42 / 72

Canvas - Dive Into HTML5

7/2/13

Imagine yo ure drawing a picture in ink. Yo u do nt want to just dive in and start drawing with ink, because yo u might make a mistake. Instead, yo u sketch the lines and curves with a pencil, and o nce yo ure happy with it, yo u trace o ver yo ur sketch in ink. Each canvas has a path. Defining the path is like drawing with a pencil. Yo u can draw whatever yo u like, but it wo nt be part o f the finished pro duct until yo u pick up the quill and trace o ver yo ur path in ink. To draw straight lines in pencil, yo u use the fo llo wing two metho ds: 1. moveTo(x, y) mo ves the pencil to the specified starting po int. 2. lineTo(x, y) draws a line to the specified ending po int. The mo re yo u call moveTo() and lineTo(), the bigger the path gets. These are pencil metho ds yo u can call them as o ften as yo u like, but yo u wo nt see anything o n the canvas until yo u call o ne o f the ink metho ds. Lets begin by drawing the o ff-white grid. for (var x = 0.5; x < 500; x += 10) { context.moveTo(x, 0); context.lineTo(x, 375); }

Draw vertical lines


for (var y = 0.5; y < 375; y += 10) { context.moveTo(0, y); context.lineTo(500, y); }

Draw horizontal lines


Tho se were all pencil metho ds. No thing has actually been drawn o n the canvas yet. We need an ink metho d to make it permanent. context.strokeStyle = "#eee"; context.stroke(); stroke() is o ne o f the ink metho ds. It takes the co mplex path yo u defined with all tho se moveTo() and lineTo() calls, and actually draws it o n the canvas. The strokeStyle co ntro ls the co lo r o f the lines. This is the result:

http://diveintohtml5.info/canvas.html

43 / 72

Canvas - Dive Into HTML5

7/2/13

ASK PRO FESSO R MARKUP

Q: Why did yo u start x and y at 0.5? Why no t 0? A: Imagine each pixel as a large square. The who le-number co o rdinates (0, 1, 2) are the edges o f the squares. If yo u draw a o ne-unit-wide line between who le-number co o rdinates, it will o verlap o ppo site sides o f the pixel square, and the resulting line will be drawn two pixels wide. To draw a line that is o nly o ne pixel wide, yo u need to shift the co o rdinates by 0.5 perpendicular to the line's directio n. Fo r example, if yo u try to draw a line fro m (1, 0) to (1, 3), the bro wser will draw a line co vering 0.5 screen pixels o n either side o f x=1. The screen cant display half a pixel, so it expands the line to co ver a to tal o f two pixels:

But, if yo u try to draw a line fro m (1.5, 0) to (1.5, 3), the bro wser will draw a line co vering 0.5 screen pixels o n either side o f x=1.5, which results in a true 1-pixel-wide line:

http://diveintohtml5.info/canvas.html

44 / 72

Canvas - Dive Into HTML5

7/2/13

Thanks to Jason Johnson for providing these diagrams.

No w lets draw the ho rizo ntal arro w. All the lines and curves o n a path are drawn in the same co lo r (o r gradient yes, well get to tho se so o n). We want to draw the arro w in a different co lo r ink black instead o f o ff-white so we need to start a new path.

A new path
context.beginPath(); context.moveTo(0, 40); context.lineTo(240, 40); context.moveTo(260, 40); context.lineTo(500, 40); context.moveTo(495, 35); context.lineTo(500, 40); context.lineTo(495, 45); The vertical arro w lo o ks much the same. Since the vertical arro w is the same co lo r as the ho rizo ntal arro w, we do no t need to start ano ther new path. The two arro ws will be part o f the same path. context.moveTo(60, 0); context.lineTo(60, 153); context.moveTo(60, 173); context.lineTo(60, 375); context.moveTo(65, 370); context.lineTo(60, 375); context.lineTo(55, 370);

Not a new path


I said these arro ws were go ing to be black, but the strokeStyle is still o ff-white. (The fillStyle and strokeStyle do nt get reset when yo u start a new path.) Thats OK, because weve just run a series o f pencil metho ds. But befo re we draw it fo r real, in ink, we need to set the strokeStyle to black. Otherwise, these two arro ws will be o ff-white, and well hardly be able to see them! The fo llo wing lines change the co lo r to black and draw the lines o n the canvas: context.strokeStyle = "#000"; context.stroke();
http://diveintohtml5.info/canvas.html 45 / 72

Canvas - Dive Into HTML5

7/2/13

This is the result:

TEXT
IE
7.0+*

FIREFOX
3.0+

SAFARI
3.0+

CHROME
3.0+

OPERA
10.0+

IPHONE
1.0+

ANDROID
1.0+

* Internet Explorer 7 and 8 require the third- party explorercanvas library. Internet Explorer 9 supports canvas text natively. Moz illa Firefox 3.0 requires a compatibility shim.
In additio n to drawing lines o n a canvas, yo u can also draw text o n a canvas. Unlike text o n the surro unding web page, there is no bo x mo del. That means no ne o f the familiar CSS layo ut techniques are available: no flo ats, no margins, no padding, no wo rd wrapping. (Maybe yo u think thats a go o d thing!) Yo u can set a few fo nt attributes, then yo u pick a po int o n the canvas and draw yo ur text there. The fo llo wing fo nt attributes are available o n the drawing co ntext: font can be anything yo u wo uld put in a CSS font rule. That includes fo nt style, fo nt variant, fo nt weight, fo nt size, line height, and fo nt family. textAlign co ntro ls text alignment. It is similar (but no t identical) to a CSS text-align rule. Po ssible values are start, end, left, right, and center. textBaseline co ntro ls where the text is drawn relative to the starting po int. Po ssible values are top, hanging, middle, alphabetic, ideographic, o r bottom. textBaseline is tricky, because text is tricky (English text isnt, but yo u can draw any Unico de character yo u like o n a canvas, and Unico de is tricky). The HTML5 specificatio n explains the different text baselines: The to p o f the em square is ro ughly at the to p o f the glyphs in a fo nt, the hanging baseline is where so me glyphs like are ancho red, the middle is half-way between the to p o f the em square and the bo tto m o f the em square, the alphabetic baseline is where characters like , , f, and are ancho red, the ideo graphic baseline is where glyphs like and are ancho red, and the bo tto m o f the em square is ro ughly at the bo tto m o f the glyphs in a fo nt. The to p and bo tto m o f the bo unding bo x can be far fro m these baselines, due to glyphs extending far o utside the em square.
http://diveintohtml5.info/canvas.html 46 / 72

Canvas - Dive Into HTML5

7/2/13

Fo r simple alphabets like English, yo u can safely stick with top, middle, o r bottom fo r the textBaseline pro perty. Lets draw so me text! Text drawn inside the canvas inherits the fo nt size and style o f the <canvas> element itself, but yo u can o verride this by setting the font pro perty o n the drawing co ntext. context.font = "bold 12px sans-serif"; context.fillText("x", 248, 43); context.fillText("y", 58, 165);

Change the font style


The fillText() metho d draws the actual text. context.font = "bold 12px sans-serif"; context.fillText("x", 248, 43); context.fillText("y", 58, 165);

Draw the text


ASK PRO FESSO R MARKUP

Q: Can I use relative fo nt sizes to draw text o n a canvas? A: Yes. Like every o ther HTML element o n yo ur page, the <canvas> element itself has a co mputed fo nt size based o n yo ur pages CSS rules. If yo u set the context.font pro perty to a relative fo nt size like 1.5em o r 150%, yo ur bro wser multiplies this by the co mputed fo nt size o f the <canvas> element itself.

Fo r the text in the upper-left co rner, lets say I want the to p o f the text to be at y=5. But Im lazy I do nt want to measure the height o f the text and calculate the baseline. Instead, I can set textBaseline to top and pass in the upper-left co o rdinate o f the texts bo unding bo x. context.textBaseline = "top"; context.fillText("( 0 , 0 )", 8, 5); No w fo r the text in the lo wer-right co rner. Lets say I want the bo tto m-right co rner o f the text to be at co o rdinates (492,370) just a few pixels away fro m the bo tto m-right co rner o f the canvas but I do nt want to measure the width o r height o f the text. I can set textAlign to right and textBaseline to bottom, then call fillText() with the bo tto m-right co o rdinates o f the texts bo unding bo x. context.textAlign = "right"; context.textBaseline = "bottom"; context.fillText("( 500 , 375 )", 492, 370);

http://diveintohtml5.info/canvas.html

47 / 72

Canvas - Dive Into HTML5

7/2/13

And this is the result:

Oo ps! We fo rgo t the do ts in the co rners. Well see ho w to draw circles a little later. Fo r no w, Ill cheat a little and draw them as rectangles. context.fillRect(0, 0, 3, 3); context.fillRect(497, 372, 3, 3);

Draw two dots


And thats all she wro te! Here is the final pro duct:

GRADIENTS
http://diveintohtml5.info/canvas.html 48 / 72

Canvas - Dive Into HTML5

7/2/13

IE
line ar gradie nt s radial gradie nt s 7.0+* 9.0+

FIREFOX
3.0+ 3.0+

SAFARI
3.0+ 3.0+

CHROME
3.0+ 3.0+

OPERA
10.0+ 10.0+

IPHONE
1.0+ 1.0+

ANDROID
1.0+ 1.0+

* Internet Explorer 7 and 8 require the third- party explorercanvas library. Internet Explorer 9 supports <canvas> gradients natively.
Earlier in this chapter, yo u learned ho w to draw a rectangle filled with a so lid co lo r, then a line stro ked with a so lid co lo r. But shapes and lines arent limited to so lid co lo rs. Yo u can do all kinds o f magic with gradients. Lets lo o k at an example.

The markup lo o ks the same as any o ther canvas. <canvas id="d" width="300" height="225"></canvas> First, we need to find the <canvas> element and its drawing co ntext. var d_canvas = document.getElementById("d"); var context = d_canvas.getContext("2d"); Once we have the drawing co ntext, we can start to define a gradient. A gradient is a smo o th transitio n between two o r mo re co lo rs. The canvas drawing co ntext suppo rts two types o f gradients: 1. createLinearGradient(x0, y0, x1, y1) paints alo ng a line fro m (x0, y0) to (x1, y1). 2. createRadialGradient(x0, y0, r0, x1, y1, r1) paints alo ng a co ne between two circles. The first three parameters represent the start circle, with o rigin (x0, y0) and radius r0. The last three parameters represent the end circle, with o rigin (x1, y1) and radius r1. Lets make a linear gradient. Gradients can be any size, but Ill make this gradient be 300 pixels wide, like the canvas.

Create a gradient object


var my_gradient = context.createLinearGradient(0, 0, 300, 0); Because the y values (the 2N D and 4T H parameters) are bo th 0, this gradient will shade evenly fro m left to right. Once we have a gradient o bject, we can define the gradients co lo rs. A gradient has two o r mo re co lo r sto ps. Co lo r sto ps can be anywhere alo ng the gradient. To add a co lo r sto p, yo u need to specify its po sitio n alo ng the gradient. Gradient po sitio ns can be anywhere between 0 to 1. Lets define a gradient that shades fro m black to white. my_gradient.addColorStop(0, "black"); my_gradient.addColorStop(1, "white");
http://diveintohtml5.info/canvas.html 49 / 72

Canvas - Dive Into HTML5

7/2/13

Defining a gradient do esnt draw anything o n the canvas. Its just an o bject tucked away in memo ry so mewhere. To draw a gradient, yo u set yo ur fillStyle to the gradient and draw a shape, like a rectangle o r a line.

Fill style is a gradient


context.fillStyle = my_gradient; context.fillRect(0, 0, 300, 225); And this is the result:

Suppo se yo u want a gradient that shades fro m to p to bo tto m. When yo u create the gradient o bject, keep the x values (1S T and 3 R D parameters) co nstant, and make the y values (2N D and 4T H parameters) range fro m 0 to the height o f the canvas.

x values are 0, y values vary


var my_gradient = context.createLinearGradient(0, 0, 0, 225); my_gradient.addColorStop(0, "black"); my_gradient.addColorStop(1, "white"); context.fillStyle = my_gradient; context.fillRect(0, 0, 300, 225); And this is the result:

Yo u can also create gradients alo ng a diago nal.

both x and y values vary


var my_gradient = context.createLinearGradient(0, 0, 300, 225);
http://diveintohtml5.info/canvas.html 50 / 72

Canvas - Dive Into HTML5

7/2/13

my_gradient.addColorStop(0, "black"); my_gradient.addColorStop(1, "white"); context.fillStyle = my_gradient; context.fillRect(0, 0, 300, 225); And this is the result:

IMAGES
IE
7.0+*

FIREFOX
3.0+

SAFARI
3.0+

CHROME
3.0+

OPERA
10.0+

IPHONE
1.0+

ANDROID
1.0+

* Internet Explorer 7 and 8 require the third- party explorercanvas library. Internet Explorer 9 supports <canvas> images natively.
Here is a cat:

An <img> element
Here is the same cat, drawn o n a canvas:

A <canvas> element

The canvas drawing co ntext defines a drawImage() metho d fo r drawing an image o n a canvas. The metho d can take three, five, o r nine arguments. drawImage(image, dx, dy) takes an image and draws it o n the canvas. The given co o rdinates (dx, dy) will be the upper-left co rner o f the image. Co o rdinates (0, 0) wo uld draw the image at the upper-left co rner o f the canvas. drawImage(image, dx, dy, dw, dh) takes an image, scales it to a width o f dw and a height o f dh, and draws it o n the canvas at co o rdinates (dx, dy).
http://diveintohtml5.info/canvas.html 51 / 72

Canvas - Dive Into HTML5

7/2/13

drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh) takes an image, clips it to the rectangle (sx, sy, sw, sh), scales it to dimensio ns (dw, dh), and draws it o n the canvas at co o rdinates (dx, dy). The HTML5 specificatio n explains the drawImage() parameters: The so urce rectangle is the rectangle [within the so urce image] who se co rners are the fo ur po ints (sx, sy), (sx+sw, sy), (sx+sw, sy+sh), (sx, sy+sh). The destinatio n rectangle is the rectangle [within the canvas] who se co rners are the fo ur po ints (dx, dy), (dx+dw, dy), (dx+dw, dy+dh), (dx, dy+dh).

To draw an image o n a canvas, yo u need an image. The image can be an existing <img> element, o r yo u can create an Image() o bject with JavaScript. Either way, yo u need to ensure that the image is fully lo aded befo re yo u can draw it o n the canvas. If yo ure using an existing <img> element, yo u can safely draw it o n the canvas during the window.onload event.

using an <img> element


<img id="cat" src="images/cat.png" alt="sleeping cat" width="177" height="113"> <canvas id="e" width="177" height="113"></canvas> <script> window.onload = function() { var canvas = document.getElementById("e"); var context = canvas.getContext("2d"); var cat = document.getElementById("cat"); context.drawImage(cat, 0, 0); }; </script> If yo ure creating the image o bject entirely in JavaScript, yo u can safely draw the image o n the canvas during the Image.onload event.

using an Image() object


<canvas id="e" width="177" height="113"></canvas> <script>
http://diveintohtml5.info/canvas.html 52 / 72

Canvas - Dive Into HTML5

7/2/13

var canvas = document.getElementById("e"); var context = canvas.getContext("2d"); var cat = new Image(); cat.src = "images/cat.png"; cat.onload = function() { context.drawImage(cat, 0, 0); }; </script> The o ptio nal 3 R D and 4T H parameters to the drawImage() metho d co ntro l image scaling. This is the same image, scaled to half its width and height and drawn repeatedly at different co o rdinates within a single canvas.

Here is the script that pro duces the multicat effect: cat.onload = function() { for (var x = 0, y = 0; x < 500 && y < 375; x += 50, y += 37) { context.drawImage(cat, x, y, 88, 56); } };

Scale the image


All this effo rt raises a legitimate questio n: why wo uld yo u want to draw an image o n a canvas in the first place? What do es the extra co mplexity o f image-o n-a-canvas buy yo u o ver an <img> element and so me CSS rules? Even the multicat effect co uld be replicated with 10 o verlapping <img> elements. The simple answer is, fo r the same reaso n yo u might want to draw text o n a canvas. The canvas co o rdinates diagram included text, lines, and shapes; the text-o n-a-canvas was just o ne part o f a larger wo rk. A mo re co mplex diagram co uld easily use drawImage() to include ico ns, sprites, o r o ther graphics.

WHAT ABOUT IE?


Versio ns o f Internet Explo rer befo re 9.0 do no t suppo rt the canvas API. (IE9 do es fully suppo rt the canvas API.) Ho wever,
http://diveintohtml5.info/canvas.html 53 / 72

Canvas - Dive Into HTML5

7/2/13

tho se o lder versio ns o f Internet Explo rer do suppo rt a Micro so ft-pro prietary techno lo gy called VML, which can do many o f the same things as the <canvas> element. And thus, excanvas.js was bo rn. Explo rercanvas (excanvas.js) is an o pen so urce, Apache-licensed JavaScript library that implements the canvas API in Internet Explo rer. To use it, include the fo llo wing <script> element at the to p o f yo ur page. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Dive Into HTML5</title> <!--[if lt IE 9]> <script src="excanvas.js"></script> <![endif]--> </head> <body> ... </body> </html> The <!--[if lt IE 9]> and <![endif]--> bits are co nditio nal co mments. Internet Explo rer interprets them like an if statement: if the current bro wser is a versio n o f Internet Explo rer prio r to (but no t including) versio n 9, then execute this blo ck. Every o ther bro wser will treat the entire blo ck as an HTML co mment. The net result is that Internet Explo rer 7 and 8 will do wnlo ad the excanvas.js script and execute it, but o ther bro wsers will igno re the script alto gether (no t do wnlo ad it, no t execute it, no t anything). This makes yo ur page lo ad faster in bro wsers that implement the canvas API natively. Once yo u include the excanvas.js in the <head> o f yo ur page, yo u do nt need to do anything else to acco mo date Internet Explo rer. Just include <canvas> elements in yo ur markup, o r create them dynamically with JavaScript. Fo llo w the instructio ns in this chapter to get the drawing co ntext o f a <canvas> element, and yo u can draw shapes, text, and patterns. Well no t quite. There are a few limitatio ns: 1. Gradients can o nly be linear. Radial gradients are no t suppo rted. 2. Patterns must be repeating in bo th directio ns. 3. Clipping regio ns are no t suppo rted. 4. No n-unifo rm scaling do es no t co rrectly scale stro kes. 5. Its slo w. This sho uld no t co me as a raging sho ck to anyo ne, since Internet Explo rer's JavaScript parser is slo wer than o ther bro wsers to begin with. Once yo u start drawing co mplex shapes via a JavaScript library that translates co mmands to a co mpletely different techno lo gy, things are go ing to get bo gged do wn. Yo u wo nt no tice the perfo rmance degradatio n in simple examples like drawing a few lines and transfo rming an image, but yo ull see it right away o nce yo u start do ing canvas-based animatio n and o ther crazy stuff. There is o ne mo re caveat abo ut using excanvas.js, and its a pro blem that I ran into while creating the examples in this chapter. Explo rerCanvas initializes its o wn faux-canvas interface auto matically whenever yo u include the excanvas.js script in yo ur HTML page. But that do esnt mean that Internet Explo rer is ready to use it immediately. In certain situatio ns, yo u can run into a race co nditio n where the faux-canvas interface is almost, but no t quite, ready to use. The primary sympto m o f this state is that Internet Explo rer will co mplain that object doesnt support this property or method whenever yo u try to do anything with a <canvas> element, such as get its drawing co ntext. The easiest so lutio n to this is to defer all o f yo ur canvas-related manipulatio n until after the onload event fires. This may be a while if yo ur page has a lo t o f images o r video s, they will delay the onload event but it will give Explo rerCanvas time to wo rk its magic.

A COMPLETE, LIVE EXAMPLE


http://diveintohtml5.info/canvas.html 54 / 72

Canvas - Dive Into HTML5

7/2/13

Halma is a centuries-o ld bo ard game. Many variatio ns exist. In this example, Ive created a so litaire versio n o f Halma with 9 pieces o n a 9 9 bo ard. In the beginning o f the game, the pieces fo rm a 3 3 square in the bo tto m-left co rner o f the bo ard. The o bject o f the game is to mo ve all the pieces so they fo rm a 3 3 square in the upper-right co rner o f the bo ard, in the least number o f mo ves. There are two types o f legal mo ves in Halma: Take a piece and mo ve it to any adjacent empty square. An empty square is o ne that do es no t currently have a piece in it. An adjacent square is immediately no rth, so uth, east, west, no rthwest, no rtheast, so uthwest, o r so utheast o f the pieces current po sitio n. (The bo ard do es no t wrap aro und fro m o ne side to the o ther. If a piece is in the left-mo st co lumn, it can no t mo ve west, no rthwest, o r so uthwest. If a piece is in the bo tto m-mo st ro w, it can no t mo ve so uth, so utheast, o r so uthwest.) Take a piece and ho p o ver an adjacent piece, and po ssibly repeat. That is, if yo u ho p o ver an adjacent piece, then ho p o ver another piece adjacent to yo ur new po sitio n, that co unts as a single mo ve. In fact, any number o f ho ps still co unts as a single mo ve. (Since the go al is to minimize the to tal number o f mo ves, do ing well in Halma invo lves co nstructing, and then using, lo ng chains o f staggered pieces so that o ther pieces can ho p o ver them in lo ng sequences.) Here is the game itself. Yo u can also play it o n a separate page if yo u want to po ke at it with yo ur bro wsers develo per to o ls.

Moves: 0
Ho w do es it wo rk? Im so glad yo u asked. I wo nt sho w all the co de here. (Yo u can see it at diveinto html5.info /examples/halma.js.) Ill skip o ver mo st o f the gameplay co de itself, but I want to highlight a few parts o f the co de that deal with actually drawing o n the canvas and respo nding to mo use clicks o n the canvas element. During page lo ad, we initialize the game by setting the dimensio ns o f the <canvas> itself and sto ring a reference to its drawing co ntext. gCanvasElement.width = kPixelWidth; gCanvasElement.height = kPixelHeight;
http://diveintohtml5.info/canvas.html 55 / 72

Canvas - Dive Into HTML5

7/2/13

gDrawingContext = gCanvasElement.getContext("2d"); Then we do so mething yo u havent seen yet: we add an event listener to the <canvas> element to listen fo r click events. gCanvasElement.addEventListener("click", halmaOnClick, false); The halmaOnClick() functio n gets called when the user clicks anywhere within the canvas. Its argument is a MouseEvent o bject that co ntains info rmatio n abo ut where the user clicked. function halmaOnClick(e) { var cell = getCursorPosition(e); // the rest of this is just gameplay logic for (var i = 0; i < gNumPieces; i++) { if ((gPieces[i].row == cell.row) && (gPieces[i].column == cell.column)) { clickOnPiece(i); return; } } clickOnEmptyCell(cell); } The next step is to take the MouseEvent o bject and calculate which square o n the Halma bo ard just go t clicked. The Halma bo ard takes up the entire canvas, so every click is somewhere o n the bo ard. We just need to figure o ut where. This is tricky, because mo use events are implemented differently in just abo ut every bro wser. function getCursorPosition(e) { var x; var y; if (e.pageX != undefined && e.pageY != undefined) { x = e.pageX; y = e.pageY; } else { x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; } At this po int, we have x and y co o rdinates that are relative to the do cument (that is, the entire HTML page). Thats no t quite useful yet. We want co o rdinates relative to the canvas. x -= gCanvasElement.offsetLeft; y -= gCanvasElement.offsetTop; No w we have x and y co o rdinates that are relative to the canvas. That is, if x is 0 and y is 0 at this po int, we kno w that the user just clicked the to p-left pixel o f the canvas. Fro m here, we can calculate which Halma square the user clicked, and then act acco rdingly. var cell = new Cell(Math.floor(y/kPieceHeight), Math.floor(x/kPieceWidth)); return cell; }
http://diveintohtml5.info/canvas.html 56 / 72

Canvas - Dive Into HTML5

7/2/13

Whew! Mo use events are to ugh. But yo u can use the same lo gic (in fact, this exact co de) in all o f yo ur o wn canvas-based applicatio ns. Remember: mo use click do cument-relative co o rdinates canvas-relative co o rdinates applicatio nspecific co de. OK, lets lo o k at the main drawing ro utine. Because the graphics are so simple, Ive cho sen to clear and redraw the bo ard in its entirety every time anything changes within the game. This is no t strictly necessary. The canvas drawing co ntext will retain whatever yo u have previo usly drawn o n it, even if the user scro lls the canvas o ut o f view o r changes to ano ther tab and then co mes back later. If yo ure develo ping a canvas-based applicatio n with mo re co mplicated graphics (such as an arcade game), yo u can o ptimize perfo rmance by tracking which regio ns o f the canvas are dirty and redrawing just the dirty regio ns. But that is o utside the sco pe o f this bo o k. gDrawingContext.clearRect(0, 0, kPixelWidth, kPixelHeight); The bo ard-drawing ro utine sho uld lo o k familiar. Its similar to ho w we drew the canvas co o rdinates diagram earlier in this chapter. gDrawingContext.beginPath(); /* vertical lines */ for (var x = 0; x <= kPixelWidth; x += kPieceWidth) { gDrawingContext.moveTo(0.5 + x, 0); gDrawingContext.lineTo(0.5 + x, kPixelHeight); } /* horizontal lines */ for (var y = 0; y <= kPixelHeight; y += kPieceHeight) { gDrawingContext.moveTo(0, 0.5 + y); gDrawingContext.lineTo(kPixelWidth, 0.5 + } /* draw it! */ gDrawingContext.strokeStyle = "#ccc"; gDrawingContext.stroke(); The real fun begins when we go to draw each o f the individual pieces. A piece is a circle, so mething we havent drawn befo re. Furthermo re, if the user selects a piece in anticipatio n o f mo ving it, we want to draw that piece as a filled-in circle. Here, the argument p represents a piece, which has row and column pro perties that deno te the pieces current lo catio n o n the bo ard. We use so me in-game co nstants to translate (column, row) into canvas-relative (x, y) co o rdinates, then draw a circle, then (if the piece is selected) fill in the circle with a so lid co lo r. function drawPiece(p, selected) { var column = p.column; var row = p.row; var x = (column * kPieceWidth) + (kPieceWidth/2); var y = (row * kPieceHeight) + (kPieceHeight/2); var radius = (kPieceWidth/2) - (kPieceWidth/10); Thats the end o f the game-specific lo gic. No w we have (x, y) co o rdinates, relative to the canvas, fo r the center o f the circle we want to draw. There is no circle() metho d in the canvas API, but there is an arc() metho d. And really, what is a circle but an arc that go es all the way aro und? Do yo u remember yo ur basic geo metry? The arc() metho d takes a center po int (x, y), a radius, a start and end angle (in radians), and a directio n flag (false fo r clo ckwise, true fo r co unter-clo ckwise). Yo u can use the Math mo dule thats built into JavaScript to calculate radians. gDrawingContext.beginPath();
http://diveintohtml5.info/canvas.html 57 / 72

y);

Canvas - Dive Into HTML5

7/2/13

gDrawingContext.arc(x, y, radius, 0, Math.PI * 2, false); gDrawingContext.closePath(); But wait! No thing has been drawn yet. Like moveTo() and lineTo, the arc() metho d is a pencil metho d. To actually draw the circle, we need to set the strokeStyle and call stroke() to trace it in ink. gDrawingContext.strokeStyle = "#000"; gDrawingContext.stroke(); What if the piece is selected? We can re-use the same path we created to draw the o utline o f the piece, to fill in the circle with a so lid co lo r. if (selected) { gDrawingContext.fillStyle = "#000"; gDrawingContext.fill(); } And thats well, thats pretty much it. The rest o f the pro gram is game-specific lo gic distinguishing between valid and invalid mo ves, keeping track o f the number o f mo ves, detecting whether the game is o ver. With 9 circles, a few straight lines, and 1 onclick handler, weve created an entire game in <canvas>. Huzzah!

FURTHER READING
Canvas tuto rial o n Mo zilla Develo per Center HTML5 canvas the basics, by Mihai Sucan CanvasDemo s.co m: demo s, to o ls, and tuto rials fo r the HTML canvas element The canvas element in the HTML5 draft standard Internet Explo rer 9 Guide fo r Develo pers: HTML5 canvas element This has been Lets Call It A Draw(ing Surface). The full table o f co ntents has mo re if yo ud like to keep reading.

DID YO U KNO W? In asso ciatio n with Go o gle Press, OReilly is distributing this bo o k in a variety o f fo rmats, including paper, ePub, Mo bi, and DRM-free PDF. The paid editio n is called HTML5: Up & Running, and it is available no w. This chapter is included in the paid editio n. If yo u liked this chapter and want to sho w yo ur appreciatio n, yo u can buy HTML5: Up & Running with this affiliate link o r buy an electro nic editio n directly fro m OReilly. Yo ull get a bo o k, and Ill get a buck. I do no t currently accept direct do natio ns.

Co pyright MMIXMMXI Mark Pilgrim

http://diveintohtml5.info/canvas.html

58 / 72

Local Storage - Dive Into HTML5

7/2/13

Yo u are here: Ho me Dive Into HTML5

THE PAST, PRESENT & FUTURE OF LOCAL STORAGE FOR WEB APPLICATIONS
sho w table o f co ntents

DIVING IN

ersistent lo cal sto rage is o ne o f the areas where native client applicatio ns have held an advantage o ver web applicatio ns. Fo r native applicatio ns, the o perating system typically pro vides an abstractio n layer fo r sto ring and retrieving applicatio n-specific data like preferences o r runtime state. These values may be sto red in the

registry, INI files, XML files, o r so me o ther place acco rding to platfo rm co nventio n. If yo ur native client applicatio n needs lo cal sto rage beyo nd key/value pairs, yo u can embed yo ur o wn database, invent yo ur o wn file fo rmat, o r any number o f o ther so lutio ns. Histo rically, web applicatio ns have had no ne o f these luxuries. Co o kies were invented early in the webs histo ry, and indeed they can be used fo r persistent lo cal sto rage o f small amo unts o f data. But they have three po tentially dealbreaking do wnsides: Co o kies are included with every HTTP request, thereby slo wing do wn yo ur web applicatio n by needlessly transmitting the same data o ver and o ver Co o kies are included with every HTTP request, thereby sending data unencrypted o ver the internet (unless yo ur entire web applicatio n is served o ver SSL) Co o kies are limited to abo ut 4 KB o f data eno ugh to slo w do wn yo ur applicatio n (see abo ve), but no t eno ugh to be terribly useful What we really want is a lo t o f sto rage space o n the client that persists beyo nd a page refresh and isnt transmitted to the server Befo re HTML5, all attempts to achieve this were ultimately unsatisfacto ry in different ways.

A BRIEF HISTORY OF LOCAL STORAGE HACKS BEFORE HTML5


In the beginning, there was o nly Internet Explo rer. Or at least, thats what Micro so ft wanted the wo rld to think. To that end, as part o f the First Great Bro wser Wars, Micro so ft invented a great many things and included them in their bro wser-to -endall-bro wser-wars, Internet Explo rer. One o f these things was called DHTML Behavio rs, and o ne o f these behavio rs was called userData. userData allo ws web pages to sto re up to 64 KB o f data per do main, in a hierarchical XML-based structure. (Trusted do mains, such as intranet sites, can sto re 10 times that amo unt. And hey, 640 KB o ught to be eno ugh fo r anybo dy.) IE do es no t present any fo rm o f permissio ns dialo g, and there is no allo wance fo r increasing the amo unt o f sto rage available. In 2002, Ado be intro duced a feature in Flash 6 that gained the unfo rtunate and misleading name o f Flash co o kies. Within the Flash enviro nment, the feature is pro perly kno wn as Lo cal Shared Objects. Briefly, it allo ws Flash o bjects to sto re up to 100 KB o f data per do main. Brad Neuberg develo ped an early pro to type o f a Flash-to -JavaScript bridge called AMASS (AJAX Massive Sto rage System), but it was limited by so me o f Flashs design quirks. By 2006, with the advent o f
http://diveintohtml5.info/storage.html 59 / 72

Local Storage - Dive Into HTML5

7/2/13

ExternalInterface in Flash 8, accessing LSOs fro m JavaScript became an o rder o f magnitude easier and faster. Brad rewro te AMASS and integrated it into the po pular Do jo To o lkit under the mo niker dojox.storage. Flash gives each do main 100 KB o f sto rage fo r free. Beyo nd that, it pro mpts the user fo r each o rder o f magnitude increase in data sto rage (1 Mb, 10 Mb, and so o n). In 2007, Go o gle launched Gears, an o pen so urce bro wser plugin aimed at pro viding additio nal capabilities in bro wsers. Gears pro vided an API to an embedded SQL database based o n SQLite. By 2010, Go o gle had shifted effo rts to ward bringing all o f the Gears capabilities into web standards like HTML5, and eventually Go o gle Gears was disco ntinued. In the meantime, Brad Neuberg and o thers co ntinued to hack away o n dojox.storage to pro vide a unified interface to all these different plugins and APIs. By 2009, dojox.storage co uld auto -detect (and pro vide a unified interface o n to p o f) Ado be Flash, Gears, Ado be AIR, and an early pro to type o f HTML5 sto rage that was o nly implemented in o lder versio ns o f Firefo x. As yo u survey these so lutio ns, a pattern emerges: all o f them are either specific to a single bro wser, o r reliant o n a thirdparty plugin. Despite hero ic effo rts to paper o ver the differences (in dojox.storage), they all expo se radically different interfaces, have different sto rage limitatio ns, and present different user experiences. So this is the pro blem that HTML5 set o ut to so lve: to pro vide a standardized API, implemented natively and co nsistently in multiple bro wsers, witho ut having to rely o n third-party plugins.

INTRODUCING HTML5 STORAGE


What I will refer to as HTML5 Sto rage is a specificatio n named Web Sto rage, which was at o ne time part o f the HTML5 specificatio n pro per, but was split o ut into its o wn specificatio n fo r uninteresting po litical reaso ns. Certain bro wser vendo rs also refer to it as Lo cal Sto rage o r DOM Sto rage. The naming situatio n is made even mo re co mplicated by so me related, similarly-named, emerging standards that Ill discuss later in this chapter. So what is HTML5 Sto rage? Simply put, its a way fo r web pages to sto re named key/value pairs lo cally, within the client web bro wser. Like co o kies, this data persists even after yo u navigate away fro m the web site, clo se yo ur bro wser tab, exit yo ur bro wser, o r what have yo u. Unlike co o kies, this data is never transmitted to the remo te web server (unless yo u go o ut o f yo ur way to send it manually). Unlike all previo us attempts at pro viding persistent lo cal sto rage, it is implemented natively in web bro wsers, so it is available even when third-party bro wser plugins are no t. Which bro wsers? Well, the latest versio n o f pretty much every bro wser suppo rts HTML5 Sto rage even Internet Explo rer!

IE
8.0+

FIREFOX
3.5+

SAFARI
4.0+

HTML5 STORAGE SUPPORT CHROME OPERA


4.0+ 10.5+

IPHONE
2.0+

ANDROID
2.0+

Fro m yo ur JavaScript co de, yo ull access HTML5 Sto rage thro ugh the localStorage o bject o n the glo bal window o bject. Befo re yo u can use it, yo u sho uld detect whether the bro wser suppo rts it.

check for HTML5 Storage


function supports_html5_storage() { try { return 'localStorage' in window && window['localStorage'] !== null; } catch (e) { return false; } } Instead o f writing this functio n yo urself, yo u can use Mo dernizr to detect suppo rt fo r HTML5 Sto rage.
http://diveintohtml5.info/storage.html 60 / 72

Local Storage - Dive Into HTML5

7/2/13

if (Modernizr.localstorage) { // window.localStorage is available! } else { // no native support for HTML5 storage :( // maybe try dojox.storage or a third-party solution }

USING HTML5 STORAGE


HTML5 Sto rage is based o n named key/value pairs. Yo u sto re data based o n a named key, then yo u can retrieve that data with the same key. The named key is a string. The data can be any type suppo rted by JavaScript, including strings, Bo o leans, integers, o r flo ats. Ho wever, the data is actually sto red as a string. If yo u are sto ring and retrieving anything o ther than strings, yo u will need to use functio ns like parseInt() o r parseFloat() to co erce yo ur retrieved data into the expected JavaScript datatype. interface Storage { getter any getItem(in DOMString key); setter creator void setItem(in DOMString key, in any data); }; Calling setItem() with a named key that already exists will silently o verwrite the previo us value. Calling getItem() with a no n-existent key will return null rather than thro w an exceptio n. Like o ther JavaScript o bjects, yo u can treat the localStorage o bject as an asso ciative array. Instead o f using the getItem() and setItem() metho ds, yo u can simply use square brackets. Fo r example, this snippet o f co de: var foo = localStorage.getItem("bar"); // ... localStorage.setItem("bar", foo); co uld be rewritten to use square bracket syntax instead: var foo = localStorage["bar"]; // ... localStorage["bar"] = foo; There are also metho ds fo r remo ving the value fo r a given named key, and clearing the entire sto rage area (that is, deleting all the keys and values at o nce). interface Storage { deleter void removeItem(in DOMString key); void clear(); }; Calling removeItem() with a no n-existent key will do no thing. Finally, there is a pro perty to get the to tal number o f values in the sto rage area, and to iterate thro ugh all o f the keys by index (to get the name o f each key). interface Storage { readonly attribute unsigned long length; getter DOMString key(in unsigned long index); };
http://diveintohtml5.info/storage.html 61 / 72

Local Storage - Dive Into HTML5

7/2/13

If yo u call key() with an index that is no t between 0(length-1), the functio n will return null.

TRACKING CHANGES TO THE HTML5 STORAGE AREA


If yo u want to keep track pro grammatically o f when the sto rage area changes, yo u can trap the storage event. The storage event is fired o n the window o bject whenever setItem(), removeItem(), o r clear() is called and actually changes something . Fo r example, if yo u set an item to its existing value o r call clear() when there are no named keys, the storage event will no t fire, because no thing actually changed in the sto rage area. The storage event is suppo rted everywhere the localStorage o bject is suppo rted, which includes Internet Explo rer 8. IE 8 do es no t suppo rt the W3C standard addEventListener (altho ugh that will finally be added in IE 9). Therefo re, to ho o k the storage event, yo ull need to check which event mechanism the bro wser suppo rts. (If yo uve do ne this befo re with o ther events, yo u can skip to the end o f this sectio n. Trapping the storage event wo rks the same as every o ther event yo uve ever trapped. If yo u prefer to use jQuery o r so me o ther JavaScript library to register yo ur event handlers, yo u can do that with the storage event, to o .) if (window.addEventListener) { window.addEventListener("storage", handle_storage, false); } else { window.attachEvent("onstorage", handle_storage); }; The handle_storage callback functio n will be called with a StorageEvent o bject, except in Internet Explo rer where the event o bject is sto red in window.event. function handle_storage(e) { if (!e) { e = window.event; } } At this po int, the variable e will be a StorageEvent o bject, which has the fo llo wing useful pro perties.

STORAGEEVENT OBJECT PROPERTY


key oldValue newValue url*

TYPE DESCRIPTION
string any any string the named key that was added, remo ved, o r mo dified the previo us value (no w o verwritten), o r null if a new item was added the new value, o r null if an item was remo ved the page which called a metho d that triggered this change

* Note: the url property was originally called uri. Some browsers shipped with that property before the specification changed. For maximum compatibility, you should check whether the url property exists, and if not, check for the uri property instead.
The storage event is no t cancelable. Fro m within the handle_storage callback functio n, there is no way to sto p the change fro m o ccurring. Its simply a way fo r the bro wser to tell yo u, hey, this just happened. Theres no thing yo u can do abo ut it no w; I just wanted to let yo u kno w.

LIMITATIONS IN CURRENT BROWSERS


In talking abo ut the histo ry o f lo cal sto rage hacks using third-party plugins, I made a po int o f mentio ning the limitatio ns o f each technique, such as sto rage limits. I just realized that I havent mentio ned anything abo ut the limitatio ns o f the no wstandardized HTML5 Sto rage. Ill give yo u the answers first, then explain them. The answers, in o rder o f impo rtance, are 5 megabytes, QUOTA_EXCEEDED_ERR, and no .
http://diveintohtml5.info/storage.html 62 / 72

Local Storage - Dive Into HTML5

7/2/13

5 megabytes is ho w much sto rage space each o rigin gets by default. This is surprisingly co nsistent acro ss bro wsers, altho ugh it is phrased as no mo re than a suggestio n in the HTML5 Sto rage specificatio n. One thing to keep in mind is that yo ure sto ring strings, no t data in its o riginal fo rmat. If yo ure sto ring a lo t o f integers o r flo ats, the difference in representatio n can really add up. Each digit in that flo at is being sto red as a character, no t in the usual representatio n o f a flo ating po int number. QUOTA_EXCEEDED_ERR is the exceptio n that will get thro wn if yo u exceed yo ur sto rage quo ta o f 5 megabytes. No is the answer to the next o bvio us questio n, Can I ask the user fo r mo re sto rage space? At time o f writing (February 2011), no bro wser suppo rts any mechanism fo r web develo pers to request mo re sto rage space. So me bro wsers (like Opera) allo w the user to co ntro l each sites sto rage quo ta, but it is purely a user-initiated actio n, no t so mething that yo u as a web develo per can build into yo ur web applicatio n.

HTML5 STORAGE IN ACTION


Lets see HTML5 Sto rage in actio n. Recall the Halma game we co nstructed in the canvas chapter. Theres a small pro blem with the game: if yo u clo se the bro wser windo w mid-game, yo ull lo se yo ur pro gress. But with HTML5 Sto rage, we can save the pro gress lo cally, within the bro wser itself. Here is a live demo nstratio n. Make a few mo ves, then clo se the bro wser tab, then re-o pen it. If yo ur bro wser suppo rts HTML5 Sto rage, the demo nstratio n page sho uld magically remember yo ur exact po sitio n within the game, including the number o f mo ves yo uve made, the po sitio n o f each o f the pieces o n the bo ard, and even whether a particular piece is selected. Ho w do es it wo rk? Every time a change o ccurs within the game, we call this functio n: function saveGameState() { if (!supportsLocalStorage()) { return false; } localStorage["halma.game.in.progress"] = gGameInProgress; for (var i = 0; i < kNumPieces; i++) { localStorage["halma.piece." + i + ".row"] = gPieces[i].row; localStorage["halma.piece." + i + ".column"] = gPieces[i].column; } localStorage["halma.selectedpiece"] = gSelectedPieceIndex; localStorage["halma.selectedpiecehasmoved"] = gSelectedPieceHasMoved; localStorage["halma.movecount"] = gMoveCount; return true; } As yo u can see, it uses the localStorage o bject to save whether there is a game in pro gress (gGameInProgress, a Bo o lean). If so , it iterates thro ugh the pieces (gPieces, a JavaScript Array) and saves the ro w and co lumn number o f each piece. Then it saves so me additio nal game state, including which piece is selected (gSelectedPieceIndex, an integer), whether the piece is in the middle o f a po tentially lo ng series o f ho ps (gSelectedPieceHasMoved, a Bo o lean), and the to tal number o f mo ves made so far (gMoveCount, an integer). On page lo ad, instead o f auto matically calling a newGame() functio n that wo uld reset these variables to hard-co ded values, we call a resumeGame() functio n instead. Using HTML5 Sto rage, the resumeGame() functio n checks whether a state abo ut a game-in-pro gress is sto red lo cally. If so , it resto res tho se values using the localStorage o bject. function resumeGame() { if (!supportsLocalStorage()) { return false; } gGameInProgress = (localStorage["halma.game.in.progress"] == "true"); if (!gGameInProgress) { return false; } gPieces = new Array(kNumPieces); for (var i = 0; i < kNumPieces; i++) { var row = parseInt(localStorage["halma.piece." + i + ".row"]);
http://diveintohtml5.info/storage.html 63 / 72

Local Storage - Dive Into HTML5

7/2/13

var column = parseInt(localStorage["halma.piece." + i + ".column"]); gPieces[i] = new Cell(row, column); } gNumPieces = kNumPieces; gSelectedPieceIndex = parseInt(localStorage["halma.selectedpiece"]); gSelectedPieceHasMoved = localStorage["halma.selectedpiecehasmoved"] == "true"; gMoveCount = parseInt(localStorage["halma.movecount"]); drawBoard(); return true; } The mo st impo rtant part o f this functio n is the caveat that I mentio ned earlier in this chapter, which Ill repeat here: Data is stored as strings. If you are storing something other than a string, youll need to coerce it yourself when you retrieve it. Fo r example, the flag fo r whether there is a game in pro gress (gGameInProgress) is a Bo o lean. In the saveGameState() functio n, we just sto red it and didnt wo rry abo ut the datatype: localStorage["halma.game.in.progress"] = gGameInProgress; But in the resumeGame() functio n, we need to treat the value we go t fro m the lo cal sto rage area as a string and manually co nstruct the pro per Bo o lean value o urselves: gGameInProgress = (localStorage["halma.game.in.progress"] == "true"); Similarly, the number o f mo ves is sto red in gMoveCount as an integer. In the saveGameState() functio n, we just sto red it: localStorage["halma.movecount"] = gMoveCount; But in the resumeGame() functio n, we need to co erce the value to an integer, using the parseInt() functio n built into JavaScript: gMoveCount = parseInt(localStorage["halma.movecount"]);

BEYOND NAMED KEY-VALUE PAIRS: COMPETING VISIONS


While the past is littered with hacks and wo rkaro unds, the present co nditio n o f HTML5 Sto rage is surprisingly ro sy. A new API has been standardized and implemented acro ss all majo r bro wsers, platfo rms, and devices. As a web develo per, thats just no t so mething yo u see every day, is it? But there is mo re to life than 5 megabytes o f named key/value pairs, and the future o f persistent lo cal sto rage is ho w shall I put it well, there are co mpeting visio ns. One visio n is an acro nym that yo u pro bably kno w already: SQL. In 2007, Go o gle launched Gears, an o pen so urce cro ssbro wser plugin which included an embedded database based o n SQLite. This early pro to type later influenced the creatio n o f the Web SQL Database specificatio n. Web SQL Database (fo rmerly kno wn as WebDB) pro vides a thin wrapper aro und a SQL database, allo wing yo u to do things like this fro m JavaScript:

actual working code in 4 browsers


openDatabase('documents', '1.0', 'Local document storage', 5*1024*1024, function (db) { db.changeVersion('', '1.0', function (t) { t.executeSql('CREATE TABLE docids (id, name)'); }, error); }); As yo u can see, mo st o f the actio n resides in the string yo u pass to the executeSql metho d. This string can be any
http://diveintohtml5.info/storage.html 64 / 72

Local Storage - Dive Into HTML5

7/2/13

suppo rted SQL statement, including SELECT, UPDATE, INSERT, and DELETE statements. Its just like backend database pro gramming, except yo ure do ing it fro m JavaScript! Oh jo y! The Web SQL Database specificatio n has been implemented by fo ur bro wsers and platfo rms.

IE

FIREFOX

SAFARI
4.0+

WEB SQL DATABASE SUPPORT CHROME OPERA


4.0+ 10.5+

IPHONE
3.0+

ANDROID
2.0+

Of co urse, if yo uve used mo re than o ne database pro duct in yo ur life, yo u are aware that SQL is mo re o f a marketing term than a hard-and-fast standard. (So me wo uld say the same o f HTML5, but never mind that.) Sure, there is an actual SQL specificatio n (its called SQL-92), but there is no database server in the wo rld that co nfo rms to that and o nly that specificatio n. Theres Oracles SQL, Micro so fts SQL, MySQLs SQL, Po stgreSQLs SQL, and SQLites SQL. Indeed, each o f these pro ducts adds new SQL features o ver time, so even saying SQLites SQL is no t sufficient to pin do wn exactly what yo ure talking abo ut. Yo u need to say the versio n o f SQL that shipped with SQLite versio n X.Y.Z. All o f which brings us to the fo llo wing disclaimer, currently residing at the to p o f the Web SQL Database specificatio n: This specificatio n has reached an impasse: all interested implemento rs have used the same SQL backend (Sqlite), but we need multiple independent implementatio ns to pro ceed alo ng a standardisatio n path. Until ano ther implemento r is interested in implementing this spec, the descriptio n o f the SQL dialect has been left as simply a reference to Sqlite, which isn't acceptable fo r a standard. It is against this backdro p that I will intro duce yo u to ano ther co mpeting visio n fo r advanced, persistent, lo cal sto rage fo r web applicatio ns: the Indexed Database API, fo rmerly kno wn as WebSimpleDB, no w affectio nately kno wn as IndexedDB. The Indexed Database API expo ses whats called an object store . An o bject sto re shares many co ncepts with a SQL database. There are databases with reco rds, and each reco rd has a set number o f fields. Each field has a specific datatype, which is defined when the database is created. Yo u can select a subset o f reco rds, then enumerate them with a curso r. Changes to the o bject sto re are handled within transactio ns. If yo uve do ne any SQL database pro gramming, these terms pro bably so und familiar. The primary difference is that the o bject sto re has no structured query language. Yo u do nt co nstruct a statement like "SELECT * from USERS where ACTIVE = 'Y'". Instead, yo u use metho ds pro vided by the o bject sto re to o pen a curso r o n the database named USERS, enumerate thro ugh the reco rds, filter o ut reco rds fo r inactive users, and use accesso r metho ds to get the values o f each field in the remaining reco rds. An early walk-thro ugh o f IndexedDB is a go o d tuto rial o f ho w IndexedDB wo rks, giving side-by-side co mpariso ns o f IndexedDB and Web SQL Database. At time o f writing, IndexedDB has o nly been implemented in a beta versio n o f Firefo x 4. (By co ntrast, Mo zilla has stated that they will never implement Web SQL Database.) Go o gle has stated that they are co nsidering IndexedDB suppo rt fo r Chro mium and Go o gle Chro me. And even Micro so ft has said that IndexedDB is a great so lutio n fo r the web. So what can yo u, as a web develo per, do with IndexedDB? At the mo ment, virtually no thing beyo nd so me techno lo gy demo s. A year fro m no w? Maybe so mething. Check the Further Reading sectio n fo r links to so me go o d tuto rials to get yo u started.

FURTHER READING
HTML5 sto rage: HTML5 Sto rage specificatio n Intro ductio n to DOM Sto rage o n MSDN Web Sto rage: easier, mo re po werful client-side data sto rage o n Opera Develo per Co mmunity
http://diveintohtml5.info/storage.html 65 / 72

Local Storage - Dive Into HTML5

7/2/13

DOM Sto rage o n Mo zilla Develo per Center. (No te: mo st o f this page is devo ted to Firefo xs pro to type implementatio n o f a globalStorage o bject, a no n-standard precurso r to localStorage. Mo zilla added suppo rt fo r the standard localStorage interface in Firefo x 3.5.) Unlo ck lo cal sto rage fo r mo bile Web applicatio ns with HTML5, a tuto rial o n IBM Develo perWo rks Early wo rk by Brad Neuberg et. al. (pre-HTML5): Internet Explo rer Has Native Suppo rt fo r Persistence?!?! (abo ut the userData o bject in IE) Do jo Sto rage, part o f a larger tuto rial abo ut the (no w-defunct) Do jo Offline library dojox.storage.manager API reference do jo x.sto rage Subversio n repo sito ry Web SQL Database: Web SQL Database specificatio n Intro ducing Web SQL Databases Web Database demo nstratio n persistence.js, an asynchro no us JavaScript ORM built o n to p o f Web SQL Database and Gears IndexedDB: Indexed Database API specificatio n Beyo nd HTML5: Database APIs and the Ro ad to IndexedDB Firefo x 4: An early walk-thro ugh o f IndexedDB This has been The Past, Present & Future o f Lo cal Sto rage fo r Web Applicatio ns. The full table o f co ntents has mo re if yo ud like to keep reading.

DID YO U KNO W? In asso ciatio n with Go o gle Press, OReilly is distributing this bo o k in a variety o f fo rmats, including paper, ePub, Mo bi, and DRM-free PDF. The paid editio n is called HTML5: Up & Running, and it is available no w. This chapter is included in the paid editio n. If yo u liked this chapter and want to sho w yo ur appreciatio n, yo u can buy HTML5: Up & Running with this affiliate link o r buy an electro nic editio n directly fro m OReilly. Yo ull get a bo o k, and Ill get a buck. I do no t currently accept direct do natio ns.

Co pyright MMIXMMXI Mark Pilgrim

http://diveintohtml5.info/storage.html

66 / 72

CSS3 Transition
Search w3schools.com: Nyelv kivlas z ts a HOME HTML CSS JAVASCRIPT JQUERY XML ASP.NET PHP SQL MORE...
REFERENC ES | EXAMP LES | FO RUM

7/2/13

| ABO UT

Get Cert ified


Study Web Technologies and get a diploma at w3schools.com

SHARE T HIS PAGE

Like

70k

CSS3 Tutorial
CSS3 HOME CSS3 Introduction CSS3 Borders CSS3 Backgrounds CSS3 Text Effects CSS3 Fonts CSS3 2D Transforms CSS3 3D Transforms CSS3 T ransit ions CSS3 Animations CSS3 Multiple Columns CSS3 User Interface

CSS3 Transitions
Previous Next Chapter

WEB HOST ING


Bes t Web Ho s ting eUK Web Ho s ting UK Res eller Ho s ting Clo ud Ho s ting

CSS3 Transitions
With CSS3, we can add an effect when changing from one style to another, without using Flash animations or JavaScripts. Mouse over the element below:

WEB BUILDING
Do wnlo ad XML Edito r FREE Webs ite BUILDER FREE Webs ite Creato r Bes t Webs ite Templates

CSS3 References
CSS3 Reference CSS3 Browser Support CSS3 Selectors CSS3 Reference Aural CSS3 Web Safe Fonts CSS3 Units CSS3 Colors CSS3 Color Values CSS3 Color Names CSS3 Color HEX

Browser Support
Propert y transition Internet Explorer 10, Firefox, Chrome, and Opera supports the transition property. Safari requires the prefix -webkit-. Not e: Internet Explorer 9, and earlier versions, does not support the transition property. Not e: Chrome 25, and earlier versions, requires the prefix -webkit-. Browser Support

ST AT IST ICS
Bro ws er Statis tic s OS Statis tic s Dis play Statis tic s

How does it work?


CSS3 transitions are effects that let an element gradually change from one style to another. To do this, you must specify two things: Specify the CSS property you want to add an effect to Specify the duration of the effect.

Example
Transition effect on the width property, duration: 2 seconds:

div { transition: width 2s; -webkit-transition: width 2s; /* Safari */ }

Not e: If the duration is not specified, the transition will have no effect, because default value is 0. The effect will start when the specified CSS property changes value. A typical CSS property change would be when a user mouse-over an element:

Example
Specify :hover for <div> elements:

div:hover { width:300px; }
T ry it yourself Not e: When the cursor mouse out of the element, it gradually changes back to it's original style.

Multiple changes
To add a transitional effect for more than one style, add more properties, separated by commas:

Example
Add effects on the width, height, and the transformation:

div { transition: width 2s, height 2s, transform 2s; -webkit-transition: width 2s, height 2s, -webkit-transform 2s; }
http://www.w3schools.com/css3/css3_transitions.asp 67 / 72

CSS3 Transition
T ry it yourself

7/2/13

Transition Properties
The following table lists all the transition properties: Propert y transition Descript ion A shorthand property for setting the four transition properties into a single property Specifies the name of the CSS property to which the transition is applied Defines the length of time that a transition takes. Default 0 Describes how the speed during a transition will be calculated. Default "ease" Defines when the transition will start. Default 0 CSS 3

transition-property transition-duration transition-timing-function

3 3 3

transition-delay

The two examples below sets all transition properties:

Example
Use all transition properties in one example:

div { transition-property: width; transition-duration: 1s; transition-timing-function: linear; transition-delay: 2s; /* Safari */ -webkit-transition-property:width; -webkit-transition-duration:1s; -webkit-transition-timing-function:linear; -webkit-transition-delay:2s; }
T ry it yourself

Example
The same transition effects as above, using the shorthand transition property:

div { transition: width 1s linear 2s; /* Safari */ -webkit-transition:width 1s linear 2s; }


T ry it yourself

Previous

Next Chapter

Award-winning XML Tools: Altova MissionKit

The Altova MissionKit is an integrated suite of tools ideal for: XML development Web & Web services development Data mapping & integration Rendering & publishing XML & database data XBRL validation, taxonomy editing, transformation & rendering Chart & report generation for XML & XBRL Altova MissionKit includes XMLSpy - the industry leading XML editor, MapForce - a graphical, any-to-any data mapping tool, StyleVision - a visual XSLT and report designer, and much more. Youll get 7 tools for less than the price of 2! Try Altova MissionKit free for 30 days! Download a fully-funct ional free t rial

T ry it now!

http://www.w3schools.com/css3/css3_transitions.asp

68 / 72

CSS3 Transition

7/2/13

T o p 10 T ut o rials
HTML Tuto rial HTML5 Tuto rial CSS Tuto rial CSS3 Tuto rial JavaSc ript Tuto rial jQuery Tuto rial SQL Tuto rial PHP Tuto rial ASP.NET Tuto rial XML Tuto rial

T o p 10 References
HTML/HTML5 Referenc e CSS 1,2,3 Referenc e CSS 3 Bro ws er Suppo rt JavaSc ript HTML DOM XML DOM PHP Referenc e jQuery Referenc e ASP.NET Referenc e HTML Co lo rs

Examples
HTML Examples CSS Examples XML Examples JavaSc ript Examples HTML DOM Examples XML DOM Examples AJAX Examples ASP.NET Examples Raz o r Examples ASP Examples SVG Examples

Quizzes
HTML Quiz HTML5 Quiz XHTML Quiz CSS Quiz JavaSc ript Quiz jQuery Quiz XML Quiz ASP Quiz PHP Quiz SQL Quiz

Co lo r Picker

St at ist ics
Bro ws er Statis tic s Bro ws er OS Bro ws er Dis play

REPO RT ERRO R

| HO ME

| TO P

| PRINT

| FO RUM

| ABO UT

| AD VERTISE WITH US

W3Sc ho o ls is o ptimiz ed fo r learning, tes ting, and training. Examples might be s implified to impro ve reading and bas ic unders tanding. Tuto rials , referenc es , and examples are c o ns tantly reviewed to avo id erro rs , but we c anno t warrant full c o rrec tnes s o f all c o ntent. While us ing this s ite, yo u agree to have read and ac c epted o ur terms o f us e and privac y po lic y. Co pyright 1999-2013 by Refs nes Data. All Rights Res erved.

http://www.w3schools.com/css3/css3_transitions.asp

69 / 72

CSS3 Animations
Search w3schools.com: Nyelv kivlas z ts a HOME HTML CSS JAVASCRIPT JQUERY XML ASP.NET PHP SQL MORE...
REFERENC ES | EXAMP LES | FO RUM

7/2/13

| ABO UT

Get Cert ified


Study Web Technologies and get a diploma at w3schools.com

SHARE T HIS PAGE

Like

70k

CSS3 Tutorial
CSS3 HOME CSS3 Introduction CSS3 Borders CSS3 Backgrounds CSS3 Text Effects CSS3 Fonts CSS3 2D Transforms CSS3 3D Transforms CSS3 Transitions CSS3 Animat ions CSS3 Multiple Columns CSS3 User Interface

CSS3 Animations
Previous Next Chapter

WEB HOST ING


Bes t Web Ho s ting eUK Web Ho s ting UK Res eller Ho s ting Clo ud Ho s ting

CSS3 Animations
With CSS3, we can create animations, which can replace animated images, Flash animations, and JavaScripts in many web pages.

WEB BUILDING

CSS3
Animat io n

XML Edito r - Free Trial! FREE Webs ite BUILDER FREE Webs ite Creato r

CSS3 @keyframes Rule


To create animations in CSS3, you will have to learn about the @keyframes rule. The @keyframes rule is where the animation is created. Specify a CSS style inside the @keyframes rule and the animation will gradually change from the current style to the new style.

Bes t Webs ite Templates

CSS3 References
CSS3 Reference CSS3 Browser Support CSS3 Selectors CSS3 Reference Aural CSS3 Web Safe Fonts CSS3 Units CSS3 Colors CSS3 Color Values CSS3 Color Names CSS3 Color HEX

ST AT IST ICS
Bro ws er Statis tic s OS Statis tic s

Browser Support
Propert y @keyframes animation Internet Explorer 10, Firefox, and Opera supports the @keyframes rule and animation property. Chrome and Safari requires the prefix -webkit-. Not e: Internet Explorer 9, and earlier versions, does not support the @keyframe rule or animation property. Browser Support

Dis play Statis tic s

Example
@keyframes myfirst { from {background: red;} to {background: yellow;} } @-webkit-keyframes myfirst /* Safari and Chrome */ { from {background: red;} to {background: yellow;} }

CSS3 animation
When the animation is created in the @keyframe, bind it to a selector, otherwise the animation will have no effect. Bind the animation to a selector by specifying at least these two CSS3 animation properties: Specify the name of the animation Specify the duration of the animation

Example
Binding the "myfirst" animation to a div element, duration: 5 seconds:

div { animation: myfirst 5s; -webkit-animation: myfirst 5s; /* Safari and Chrome */ }
T ry it yourself Not e: You must define the name and the duration of the animation. If duration is omitted, the animation will not run, because the default value is 0.

What are Animations in CSS3?


An animation is an effect that lets an element gradually change from one style to another. You can change as many styles you want, as many times you want. Specify when the change will happen in percent, or the keywords "from" and "to", which is the same as 0% and

http://www.w3schools.com/css3/css3_animations.asp

70 / 72

CSS3 Animations
100%. 0% is the beginning of the animation, 100% is when the animation is complete. For best browser support, you should always define both the 0% and the 100% selectors.

7/2/13

Example
Change the background color when the animation is 25%, 50%, and again when the animation is 100% complete:

@keyframes myfirst { 0% {background: red;} 25% {background: yellow;} 50% {background: blue;} 100% {background: green;} } @-webkit-keyframes myfirst /* Safari and Chrome */ { 0% {background: red;} 25% {background: yellow;} 50% {background: blue;} 100% {background: green;} }
T ry it yourself

Example
Change the background color and position:

@keyframes myfirst { 0% {background: red; left:0px; top:0px;} 25% {background: yellow; left:200px; top:0px;} 50% {background: blue; left:200px; top:200px;} 75% {background: green; left:0px; top:200px;} 100% {background: red; left:0px; top:0px;} } @-webkit-keyframes myfirst /* Safari and Chrome */ { 0% {background: red; left:0px; top:0px;} 25% {background: yellow; left:200px; top:0px;} 50% {background: blue; left:200px; top:200px;} 75% {background: green; left:0px; top:200px;} 100% {background: red; left:0px; top:0px;} }
T ry it yourself

CSS3 Animation Properties


The following table lists the @keyframes rule and all the animation properties: Propert y @keyframes animation Descript ion Specifies the animation A shorthand property for all the the animation properties, except the animation-play-state property Specifies the name of the @keyframes animation Specifies how many seconds or milliseconds an animation takes to complete one cycle. Default 0 Describes how the animation will progress over one cycle of its duration. Default "ease" Specifies when the animation will start. Default 0 Specifies the number of times an animation is played. Default 1 Specifies whether or not the animation should play in reverse on alternate cycles. Default "normal" Specifies whether the animation is running or paused. Default "running" CSS 3 3

animation-name animation-duration

3 3

animation-timing-function

animation-delay animation-iteration-count animation-direction

3 3 3

animation-play-state

The two examples below sets all the animation properties:

Example
Run an animation called myfirst, with all the animation properties set:

div { animation-name: myfirst; animation-duration: 5s; animation-timing-function: linear; animation-delay: 2s; animation-iteration-count: infinite; animation-direction: alternate; animation-play-state: running; /* Safari and Chrome: */ -webkit-animation-name: myfirst; -webkit-animation-duration: 5s; -webkit-animation-timing-function: linear;
http://www.w3schools.com/css3/css3_animations.asp 71 / 72

CSS3 Animations

7/2/13

-webkit-animation-delay: 2s; -webkit-animation-iteration-count: infinite; -webkit-animation-direction: alternate; -webkit-animation-play-state: running; }


T ry it yourself

Example
The same animation as above, using the shorthand animation property:

div { animation: myfirst 5s linear 2s infinite alternate; /* Safari and Chrome: */ -webkit-animation: myfirst 5s linear 2s infinite alternate; }
T ry it yourself

Previous

Next Chapter

T o p 10 T ut o rials
HTML Tuto rial HTML5 Tuto rial CSS Tuto rial CSS3 Tuto rial JavaSc ript Tuto rial jQuery Tuto rial SQL Tuto rial PHP Tuto rial ASP.NET Tuto rial XML Tuto rial

T o p 10 References
HTML/HTML5 Referenc e CSS 1,2,3 Referenc e CSS 3 Bro ws er Suppo rt JavaSc ript HTML DOM XML DOM PHP Referenc e jQuery Referenc e ASP.NET Referenc e HTML Co lo rs

Examples
HTML Examples CSS Examples XML Examples JavaSc ript Examples HTML DOM Examples XML DOM Examples AJAX Examples ASP.NET Examples Raz o r Examples ASP Examples SVG Examples

Quizzes
HTML Quiz HTML5 Quiz XHTML Quiz CSS Quiz JavaSc ript Quiz jQuery Quiz XML Quiz ASP Quiz PHP Quiz SQL Quiz

Co lo r Picker

St at ist ics
Bro ws er Statis tic s Bro ws er OS Bro ws er Dis play

REPO RT ERRO R

| HO ME

| TO P

| PRINT

| FO RUM

| ABO UT

| AD VERTISE WITH US

W3Sc ho o ls is o ptimiz ed fo r learning, tes ting, and training. Examples might be s implified to impro ve reading and bas ic unders tanding. Tuto rials , referenc es , and examples are c o ns tantly reviewed to avo id erro rs , but we c anno t warrant full c o rrec tnes s o f all c o ntent. While us ing this s ite, yo u agree to have read and ac c epted o ur terms o f us e and privac y po lic y. Co pyright 1999-2013 by Refs nes Data. All Rights Res erved.

http://www.w3schools.com/css3/css3_animations.asp

72 / 72

Das könnte Ihnen auch gefallen