<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>HTML5 Doctor &#187; html5</title>
	<atom:link href="http://html5doctor.com/tag/html5/feed/" rel="self" type="application/rss+xml" />
	<link>http://html5doctor.com</link>
	<description>helping you implement HTML5 today</description>
	<lastBuildDate>Wed, 01 Feb 2012 09:28:11 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<item>
		<title>Server-Sent Events</title>
		<link>http://html5doctor.com/server-sent-events/</link>
		<comments>http://html5doctor.com/server-sent-events/#comments</comments>
		<pubDate>Tue, 24 Jan 2012 14:30:33 +0000</pubDate>
		<dc:creator>Remy Sharp</dc:creator>
				<category><![CDATA[Events]]></category>
		<category><![CDATA[JavaScript APIs]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[eventsource]]></category>
		<category><![CDATA[HTML 5]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[realtime]]></category>
		<category><![CDATA[serversentevents]]></category>
		<category><![CDATA[websockets]]></category>

		<guid isPermaLink="false">http://html5doctor.com/?p=4181</guid>
		<description><![CDATA[We've already had a glimpse at Server-Sent Events (also known as EventSource, and I'll switch between the two to keep you on your toes) in my Methods of Communication article from last year. In this article, I want to delve in to more detail about the SSE API, demonstrate its features, and even show you how to polyfill browsers that lack EventSource support.]]></description>
			<content:encoded><![CDATA[<p>We&#8217;ve already had a glimpse at <a href="http://dev.w3.org/html5/eventsource/">Server-Sent Events</a> (also known as EventSource<sup>†</sup>, and I&#8217;ll switch between the two to keep you on your toes) in my <a href="http://html5doctor.com/methods-of-communication/">Methods of Communication</a> article from last year. In this article, I want to delve in to more detail about the SSE API, demonstrate its features, and even show you how to polyfill browsers that lack EventSource support.</p>

<p>Server-Sent Events are real-time events emitted by the server and received by the browser. They&#8217;re similar to WebSockets in that they happen in real time, but they&#8217;re very much a one-way communication method <em>from</em> the server.</p>

<p>These events are similar to ordinary JavaScript events that occur in the browser — like <em>click</em> events — except we can control the name of the event and the data associated with it.</p>

<p>All the code for this article is <a href="https://github.com/remy/eventsource-h5d">available on github</a>, and a <a href="http://node.remysharp.com:8004/">live demo is available online</a>.
<span id="more-4181"></span></p>

<p><small>† Is it Server-Sent Events or EventSource? Well, they both work. Server-Sent Events is the name of the API and specification. EventSource is the name of the JavaScript object you&#8217;re instantiating. It&#8217;s a bit like Ajax and XHR, where XHR refers to the XMLHttpRequest object…kinda.</small></p>

<p><small>Two notes: a) the uptime for this example is, I&#8217;m afraid, usually rather low — good for my server, bad for you. If you test the demo locally it will give you more interesting figures. b) IE6 isn&#8217;t supported in any of this article.</small></p>

<p><section id="applications"></p>

<h2>Possible Applications <a href="#applications" class="permalink">#</a></h2>

<p>A few simple examples of applications that could make use of Server-Sent Events:</p>

<ul>
<li>A real-time chart of streaming stock prices</li>
<li>Real-time news coverage of an important event (posting links, tweets, and images)</li>
<li>A live Twitter wall fed by Twitter&#8217;s streaming API</li>
<li>A monitor for server statistics like uptime, health, and running processes</li>
</ul>

<p>We&#8217;ll use the server monitor for this article&#8217;s examples. If this application were to be used in the wild, we could also check the <code>EventSource</code>&#8216;s connection state to indicate when there&#8217;s a potential problem connecting to the server.</p>

<p></section></p>

<p><section id="api"></p>

<h2>Overview of the API <a href="#api" class="permalink">#</a></h2>

<p>The client-side API is rather simple, and it hands-down beats the insane hacks required to get real-time events to the browser back in the bad old days.</p>

<p>The main points of interest:</p>

<ul>
<li><code>new EventSource(url)</code> — this creates our <code>EventSource</code> object, which immediately starts listening for events on the given URL.</li>
<li><code>readyState</code> — as with XHR, we have a <code>readyState</code> for the <code>EventSource</code> that tells us if we&#8217;re connecting (0), open (1), or closed (2).</li>
<li><code>onopen</code>, <code>onmessage</code> — two events that we can listen for on the new <code>EventSource</code> object. By default, the <code>message</code> event will fire when new messages are received, <em>unless</em> the server explicitly sets the event type.</li>
<li><code>addEventListener</code> — not only can we listen for the default <code>message</code> event, but we can also listen for custom messages using the <code>addEventListener</code> on the <code>EventSource</code> object, just as if we were listening for a <code>click</code> event.</li>
<li><code>event.data</code> — as with most messaging APIs, the contents of the message reside in the <code>data</code> property of the <code>event</code> object. This is a string, so if we want to pass around an object, we need to encode and decode it with JSON.</li>
<li><code>close</code> — closes the connection from the client side.</li>
</ul>

<p>In the future, EventSource will also support <a href="http://www.w3.org/TR/cors/">CORS</a> using an <code>options</code> argument to the <code>EventSource</code> object: <code>{ withCredentials: true }</code>. But at the time of writing, no stable release includes this property.</p>

<p></section></p>

<p><section id="example"></p>

<h2>Simple Example <a href="#example" class="permalink">#</a></h2>

<p>Our simple web app will notify us of server status messages — things like the load average, number of currently connected users, and most CPU-intensive processes. If I were using this application in anger, I&#8217;d probably build server modules that emit specific event types when they cross specific thresholds, so that I&#8217;m only notified when something gets to warning level.</p>

<p>This snippet of JavaScript connects to our server, listens for messages, and handles the data that comes with the messages:</p>

<pre><code>var source = new EventSource('/stats');
source.onopen = function () {
  connectionOpen(true);
};

source.onerror = function () {
  connectionOpen(false);
};

source.addEventListener('connections', updateConnections, false);
source.addEventListener('requests', updateRequests, false);
source.addEventListener('uptime', updateUptime, false);

source.onmessage = function (event) {
  // a message without a type was fired
};
</code></pre>

<p></section></p>

<p><section id="properties"></p>

<h2>Properties of Server-Sent Events <a href="#properties" class="permalink">#</a></h2>

<p>Server-Sent Events are more than just a one-way web socket. They have some unique features:</p>

<ul>
<li>The connection stream is <em>from</em> the server and read-only. This suits lots of applications, some examples of which I listed above.</li>
<li>They use regular HTTP requests for the persistent connection, not a special protocol, which means we can polyfill using vanilla JavaScript.</li>
<li>If the connection drops, the <code>EventSource</code> fires an error event and automatically tries to reconnect. The server can also control the timeout before the client tries to reconnect.</li>
<li>Clients can send a unique ID with messages. When a client tries to reconnect after a dropped connection, it will send the last known ID. Then the server can see that the client missed <em>n</em> messages and send the backlog of missed messages on reconnect.</li>
</ul>

<p></section></p>

<p><section id="message-format"></p>

<h2>Message Format <a href="#message-format" class="permalink">#</a></h2>

<p>A simple message doesn&#8217;t require much:</p>

<pre><code>data: this is a simple message
&lt;blank line&gt;
</code></pre>

<p>Note that the end of a message is indicated by a blank line (obviously not the literal characters <code>&lt;blank line&gt;</code>).</p>

<p>For a message with multiple lines:</p>

<pre><code>data: this is line one
data: and this is line two
</code></pre>

<p>You can send message IDs to be used if the connection is dropped:</p>

<pre><code>id: 33
data: this is line one
data: this is line two
</code></pre>

<p>You can even send multiple messages in a single response so long as you separate the messages by blank lines:</p>

<pre><code>id: 34
data: Remy is awesome

id: 35
data: Bruce is stinky
</code></pre>

<p>And you can specify your own event types (the above messages will all trigger the <code>message</code> event):</p>

<pre><code>id: 36
event: price
data: 103.34

id: 37
event: news
data: Bruce sells his collection of replica bananas
</code></pre>

<p>You don&#8217;t have to worry about this structure on the client side. It only applies to the server, which I&#8217;ll touch on next.</p>

<p></section></p>

<p><section id="server"></p>

<h2>Typical Server <a href="#server" class="permalink">#</a></h2>

<p>I&#8217;m not going to give a full walkthrough of the server-side code, since this is an HTML5 web site <img src='http://html5doctor.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  But there are a few important and simple features that you need to know to build the server (you&#8217;ll need this part anyway if you&#8217;re going to use EventSource).</p>

<p>I&#8217;ve included <a href="https://github.com/remy/eventsource-h5d">all the files for this demo on GitHub</a> for you to peruse at your own leisure, and I&#8217;ve also deployed a <a href="http://node.remysharp.com:8004">live example of this code</a>.</p>

<p>Ideally, you should use a server that has an <a href="http://en.wikipedia.org/wiki/Event_loop">event loop</a>. This means you should <em>not</em> use Apache, but instead use a platform such as <a href="http://nodejs.org">Node.js</a> (which I&#8217;ve used) or <a href="http://twistedmatrix.com/trac/">Twisted</a> for Python.</p>

<p>Key properties:</p>

<ol>
<li>You can only accept EventSource requests if the HTTP request says it can accept the <code>event-stream</code> MIME type.</li>
<li>You need to maintain a list of all the connected users in order to emit new events.</li>
<li>You should listen for dropped connections and remove them from the list of connected users.</li>
<li>You should optionally maintain a history of messages so that reconnecting clients can catch up on missed messages.</li>
</ol>

<p>Here&#8217;s a sample of my Node.js based server.  It&#8217;s using <a href="http://senchalabs.github.com/connect/">Connect</a> (a simple webby framework for Node). When it receives a request for <code>/stats</code>, it calls the following function. I&#8217;ve commented the code so you can follow along:</p>

<pre><code>function stats(request, response) {
  // only response to an event-stream if the request 
  // actually accepts an event-stream
  if (request.headers.accept == 'text/event-stream') {

    // send the header to tell the client that we're going
    // to be streaming content down the connection
    response.writeHead(200, {
      'content-type': 'text/event-stream',
      'cache-control': 'no-cache',
      'connection': 'keep-alive'
    });

    // support the polyfill - we'll come on to this later
    if (request.headers['x-requested-with'] == 'XMLHttpRequest') {
      response.xhr = null;
    }

    // if there was a lastEventId sent in the header, send
    // the history of messages we've already stored up
    if (request.headers['last-event-id']) {
      var id = parseInt(request.headers['last-event-id']);
      for (var i = 0; i &lt; history.length; i++) {
        if (history[i].id &gt;= id) {
          sendSSE(response, history[i].id, history[i].event, history[i].message);
        }
      }
    } else {
      // if the client didn't send a lastEventId, it's the
      // first time they've come to our service, so send an
      // initial empty message with no id - this will reset
      // their id counter too.
      response.write('id\n\n');
    }

    // cache their connection - the response is where we write
    // to send messages
    connections.push(response);

    // send a broadcast message to all connected clients with
    // the total number of connections we have.
    broadcast('connections', connections.length);

    // if the connection closes to the client, remove them
    // from the connections array.
    request.on('close', function () {
      removeConnection(response);
    });
  } else {
    // if the client doesn't accept event-stream mime type,
    // send them the regular index.html page - you could do
    // anything here, including sending the client an error.
    response.writeHead(302, { location: "/index.html" });
    response.end();
  }
}
</code></pre>

<p>The important trick on the server is to ensure you <em>don&#8217;t</em> close the connection to the <code>EventSource</code> object. If you do, it will of course handle the closed connection, fire an error event, and try to reconnect. So you&#8217;ll just want to maintain the persistent connection.</p>

<p></section></p>

<p><section id="polyfills"></p>

<h2>Polyfills and Tweaks to the Server <a href="#polyfills" class="permalink">#</a></h2>

<p>There are two good polyfills I know of, and though I prefer the one I wrote, I&#8217;ll still lay them both out for you.</p>

<p><section id="yaffle"></p>

<h3>Yaffle&#8217;s Polyfill <a href="#yaffle" class="permalink">#</a></h3>

<p>The first is one by <a href="https://github.com/Yaffle">Yaffle</a> (on github), available on <a href="https://github.com/Yaffle/EventSource">github/Yaffle/eventsource</a>. </p>

<p>The cons:</p>

<ul>
<li>It doesn&#8217;t send the <code>accepts</code> header, and</li>
<li>It completely replaces the <code>EventSource</code> object, so even if your browser supports <code>EventSource</code> natively, this script will replace it. But there&#8217;s a good reason for that.</li>
</ul>

<p>The pros:</p>

<ul>
<li>It maintains a persistent connection (whereas the one we&#8217;re using doesn&#8217;t), and</li>
<li>More interestingly, it supports CORS (which I imagine is why it replaces the native <code>EventSource</code>).</li>
</ul>

<p>These two pros are quite compelling. But when I was testing, I couldn&#8217;t get it working in IE7 (which was my minimum browser target), so that might be a blocker for you…or not.</p>

<p></section></p>

<p><section id="remy"></p>

<h3>Remy&#8217;s Polyfill <a href="#remy" class="permalink">#</a></h3>

<p>The second is my own, available on <a href="https://github.com/remy/polyfills/blob/master/EventSource.js">github.com/remy/polyfills</a>.</p>

<p>The cons:</p>

<ul>
<li>It uses polling, so once a small group of messages come down, it re-establishes the connection, which could lead to significant overhead (though less so on a Node-based server). You have to add about 4 extra lines to your server code.</li>
</ul>

<p>The pros:</p>

<ul>
<li>It doesn&#8217;t replace the native <code>EventSource</code> object (but that also implies that, for now, it won&#8217;t support CORS), and</li>
<li>It supports IE7.</li>
</ul>

<p><small>Retrospectively, I might choose Yaffle&#8217;s polyfill over mine in the future if I wasn&#8217;t bothered about IE7 support.</small></p>

<p></section></p>

<p><section id="using-the-polyfill"></p>

<h3>Using the Polyfill <a href="#using-the-polyfill" class="permalink">#</a></h3>

<p>By including the <code>EventSource.js</code> JavaScript library before my client-side code, I just need a couple of small changes to my server-side code. Other than that, everything on the client side works without any changes (as a polyfill <em>should</em> work).</p>

<p>When posting the server&#8217;s reply to the client, instead of keeping the connection open, I include the following in my server when it&#8217;s finished writing the response:</p>

<pre><code>// send the data (event type, id, message, etc)
response.write(data);

// if our response contains our custom xhr property, then...
if (response.hasOwnProperty('xhr')) {
  // clear any previous timers using the xhr prop as the value
  clearTimeout(response.xhr);

  // now set a timer for 1/4 second (abritrary number) that
  // then closes the connection and removes itself from the
  // connection array.
  // The delay is in place so that a burst of messages can 
  // go out on the same connection *before* it's closed.
  response.xhr = setTimeout(function () {
    response.end();
    removeConnection(response);
  }, 250);
}
</code></pre>

<p></section>
</section></p>

<p><section id="bugs"></p>

<h2>Bugs? <a href="#bugs" class="permalink">#</a></h2>

<p>The <code>error</code> event should always fire when the <code>readyState</code> changes, assuming you didn&#8217;t explicitly call the <code>close</code> method. This works nearly all the time, but in writing this article, I found a few edge cases where it doesn&#8217;t fire. In Chrome, if I put my machine to sleep and then woke it back up, it would close the connection but not fire the event, therefore never triggering a reconnection. As I said, this is an edge case and I&#8217;ll file a bug against it, so I don&#8217;t expect it to hang around for long.</p>

<p></section></p>

<p><section id="why-not-websockets"></p>

<h2>Why Not Use WebSockets? <a href="#why-not-websockets" class="permalink">#</a></h2>

<p>There are two reasons I&#8217;d advocate using EventSource over WebSockets, as they&#8217;re currently the two contenders for sending real-time events to the browser.</p>

<p>The first is that EventSource (as we saw earlier) works over regular HTTP and can therefore be replicated entirely using JavaScript if it&#8217;s not available natively. That means that we can polyfill browsers without support, like IE9.</p>

<p>The second is probably more important: you should always use the right technology for the job. If your real-time data is sourced from your web site, <em>and</em> the user doesn&#8217;t interact in real-time, it&#8217;s likely you need Server-Sent Events. </p>

<p>I recently saw a cool <a href="http://paynedigital.com/2011/12/nodeflakes">demo of snowflakes</a> drifting down a web site. Each snowflake is a tweet based around the Christmas theme — like if someone mentions a particular Christmas-y term, it&#8217;s sucked in to the snowflake. Don&#8217;t get me wrong, I know this is a demo, and it&#8217;s very cool (if you wrote it, this is me sending you hugs), but it&#8217;s based on WebSockets. I&#8217;d suggest this demo should be based on EventSource since all the data is read-only and the user doesn&#8217;t interact with it at all.</p>

<p>The point: evaluate the technology against your problem, and aim to get good fit.</p>

<p></section>
<div id="crp_related"><h3>Related Posts:</h3><ul class="related"><li><a href="http://html5doctor.com/methods-of-communication/" rel="bookmark" class="crp_title">Methods of communication</a></li><li><a href="http://html5doctor.com/storing-data-the-simple-html5-way-and-a-few-tricks-you-might-not-have-known/" rel="bookmark" class="crp_title">Storing Data the Simple HTML5 Way (and a few tricks you might not have known)</a></li><li><a href="http://html5doctor.com/history-api/" rel="bookmark" class="crp_title">Pushing and Popping with the History API</a></li><li><a href="http://html5doctor.com/how-to-get-all-the-browsers-playing-ball/" rel="bookmark" class="crp_title">How to get all the browsers playing ball</a></li><li><a href="http://html5doctor.com/go-offline-with-application-cache/" rel="bookmark" class="crp_title">Go offline with application cache</a></li></ul></div></p>
<p><a href="http://html5doctor.com/server-sent-events/" rel="bookmark">Server-Sent Events</a> originally appeared on <a href="http://html5doctor.com">HTML5 Doctor</a> on January 24, 2012.</p>
]]></content:encoded>
			<wfw:commentRss>http://html5doctor.com/server-sent-events/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>The contenteditable attribute</title>
		<link>http://html5doctor.com/the-contenteditable-attribute/</link>
		<comments>http://html5doctor.com/the-contenteditable-attribute/#comments</comments>
		<pubDate>Tue, 10 Jan 2012 15:10:16 +0000</pubDate>
		<dc:creator>Jack Osborne</dc:creator>
				<category><![CDATA[Attributes]]></category>
		<category><![CDATA[contenteditable]]></category>
		<category><![CDATA[HTML 5]]></category>
		<category><![CDATA[html5]]></category>

		<guid isPermaLink="false">http://html5doctor.com/?p=3796</guid>
		<description><![CDATA[<p>For some time now, we’ve been using various technologies to edit and store text within a web browser. Now with the <code>contenteditable</code> attribute, things have got a whole lot easier. In this article, I’ll tell you what this attribute is for, how it works, and how we can take things further.</p>
]]></description>
			<content:encoded><![CDATA[<p>For some time now, we’ve been using various technologies to edit and store text within a web browser. Now with the <code>contenteditable</code> attribute, things have got a whole lot easier. In this article, I’ll tell you what this attribute is for, how it works, and how we can take things further.</p>

<section id="basics">
  <h2>The Basics <a href="#basics" class="permalink">#</a></h2>

  <p>First, let’s check out the spec:</p>

  <blockquote>
    <p>The <code>contenteditable</code> attribute is an enumerated attribute whose keywords are the empty string, true, and false. The empty string and the true keyword map to the true state. The false keyword maps to the false state. In addition, there is a third state, the inherit state, which is the missing value default (and the invalid value default).</p>
    <footer>— <cite><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/editing.html#contenteditable" title="contenteditable attribute — HTML5">WHATWG</a></cite></footer>
  </blockquote>

  <p>The <code>contenteditable</code> attribute was mainly intended for providing an in-browser rich-text or WYSIWYG experience. You’ve likely seen this sort of thing in blog-based authoring tools like Symphony or sites like Flickr where you can begin editing page content simply by clicking in a given area.</p>

  <p>As mentioned above, <code>contenteditable</code> has three possible states:</p>

  <dl>
    <dt><code>contenteditable=""</code> or <code>contenteditable="true"</code></dt>
    <dd>Indicates that the element is editable.</dd>

    <dt><code>contenteditable="false"</code></dt>
    <dd>Indicates that the element is not editable.</dd>

    <dt><code>contenteditable="inherit"</code></dt>
    <dd>Indicates that the element is editable if its immediate parent element is editable. This is the default value.</dd>
  </dl>

  <p>When you add <code>contenteditable</code> to an element, the browser will make that element editable. In addition, any children of that element will also become editable unless the child elements are explicitly <code>contenteditable="false"</code>.</p>
</section>

<section id="code-example">
  <h2>Code Example <a href="#code-example" class="permalink">#</a></h2>

  <p>Here’s some example code to get us started:</p>

  <figure>
    <pre><code>&#60;div id="example-one" contenteditable="true"&#62;
&#60;style scoped&#62;
  #example-one { margin-bottom: 10px; }
  [contenteditable="true"] { padding: 10px; outline: 2px dashed #CCC; }
  [contenteditable="true"]:hover { outline: 2px dashed #0090D2; }
&#60;/style&#62;
&#60;p&#62;Everything contained within this div is editable in browsers that support &#60;code&#62;HTML5&#60;/code&#62;. Go on, give it a try: click it and start typing.&#60;/p&#62;
&#60;/div&#62;
    </code></pre>
    <figcaption>Putting it together</figcaption>
  </figure>
</section>

<section id="live-examples">
  <h2>Live examples <a href="#live-examples" class="permalink">#</a></h2>
  
  <p>Here are two basic-but-live examples showing what you can do with <code>contenteditable</code>.</p>
  
  <section id="first-example">
    <h3>Example One <a href="#first-example" class="permalink">#</a></h3>
  
    <div id="example-one" contenteditable="true">
      <figure>
        <style scoped>
          #example-one { margin: 1.5em 0; }
          [contenteditable="true"] { padding: 10px; outline: 2px dashed #CCC; }
          [contenteditable="true"]:hover { outline: 2px dashed #0090D2; }
        </style>
        <p>Everything contained within this div is editable in browsers that support <code>HTML5</code>. Go on, give it a try: click it and start typing.</p>
        <figcaption>Live text editing</figcaption>
      </figure>
    </div>

    <p>I’ve used CSS to create an obvious visual cue that this area of text is different from the rest. Note that I’ve future-proofed this with <code>&#60;style scoped&#62;</code>, which <a href="http://html5doctor.com/the-scoped-attribute/">I covered in my previous article</a>.</p>
  </section>
  
  <section id="second-example">
    <h3>Example Two <a href="#second-example" class="permalink">#</a></h3>
  
    <p><a href="http://twitter.com/chriscoyier">Chris Coyier</a> of CSS-Tricks pointed out that you can let your users <a href="http://css-tricks.com/show-and-edit-style-element/">edit the CSS</a> in real-time. Because the <code>&lt;style&gt;</code> element is set to <code>display: none</code> by the user agent, we need to set it to <code>block</code> for this code to work.</p>

    <p>Try editing the <code>CSS</code> below:</p>

    <div id="example-two" contenteditable="true">
      <figure>
        <div id="style-block">
          <style contenteditable>
          #example-two {
          background: #fff;
          color: #444;
          }
          [contenteditable="true"]{
          padding: 10px;
          outline: 3px dashed #CCC;
          }
          [contenteditable="true"]:hover{
          background: rgba(255, 255, 153, 1);
          outline: 3px dashed #0090D2;
          }
          </style>
        </div>
        <figcaption>Live CSS editing</figcaption>
      </figure>
    </div>
  </section>
</section>

<section id="browser-support">
  <h2>Browser Support <a href="#browser-support" class="permalink">#</a></h2>
  
  <p>Browser support for <code>contenteditable</code> is surprisingly good:</p>
  
  <table class="wide">
    <caption>Browser Support for <code>contenteditable</code></caption>
    <thead>
      <tr>
        <th scope="col">Browser</th>
        <th scope="col">Version</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th scope="row">Chrome</th>
        <td>4.0+</td>
      </tr>
      <tr>
        <th scope="row">Safari</th>
        <td>3.1+</td>
      </tr>
      <tr>
        <th scope="row">Mobile Safari</th>
        <td>5.0+</td>
      </tr>
      <tr>
        <th scope="row">Firefox</th>
        <td>3.5+</td>
      </tr>
      <tr>
        <th scope="row">Opera</th>
        <td>9.0+</td>
      </tr>
      <tr>
        <th scope="row">Opera Mini/Mobile</th>
        <td>N/A</td>
      </tr>
      <tr>
        <th scope="row">Internet Explorer</th>
        <td>5.5+</td>
      </tr>
      <tr>
        <th scope="row">Android</th>
        <td>3.0+</td>
      </tr>
    </tbody>
  </table>

  <p>We have to give credit where it’s due and point out that Internet Explorer has supported this attribute since IE5.5. In fact, a very early iteration of <code>contenteditable</code> was <a href="http://msdn.microsoft.com/en-us/library/ms537837(VS.85).aspx">designed and implemented by Microsoft in July 2000</a>.</p>

  <p>For a more in-depth compatibility table, visit <a href="http://caniuse.com/contenteditable">When Can I Use…</a>.</p>
</section>

<section id="storing-changes">
  <h2>Storing the Changes <a href="#storing-changes" class="permalink">#</a></h2>

  <p>For this section, I went straight to Doctor Remy for help, as he is much more knowledgeable than me when it comes to <del>storing your data</del> everything.</p>

  <blockquote>
    <p>Depending on the complexity of your editable block, your code could be listening for the enter key (keyCode 13) to save the changes, and the escape key (keyCode 27) to undo the changes.</p>

    <p>When the user hits enter (assuming it’s a single line of editable content), it would grab the innerHTML of the editable field and send an Ajax post to your server with the change.</p>

    <p>A simple example of this can be seen on JS Bin: <a href="http://jsbin.com/owavu3">contenteditable saving to Ajax</a></p>

    <footer>— <cite><a href="http://html5doctor.com/author/remys/" title="Remy Sharp on storing content changes with the contenteditable attribute">Remy Sharp</a></cite></footer>
  </blockquote>
</section>

<section id="conclusion">
  <h2>Conclusion <a href="#conclusion" class="permalink">#</a></h2>
  
  <p>We’ve repeated the phrase “paving the cowpaths” all over this site, and I’m mentioning it again with the introduction of the <code>contenteditable</code> attribute. The spec finally makes official something that’s been implemented by browser makers for years.</p>

  <p>Although this is one of the lesser-known new attributes, I bet you’ll find yourself using it more often than you would think.</p>

  <p>Imagine being able to simply click a block of content and start making changes instantly: making quick corrections to an article in-place, allowing users to edit their comments, or even building spreadsheets within company applications that aren’t hooked up to any sort of back-end user interface.</p>

  <p>If you can think of other uses for this attribute, then head on down to the comments section and tell us where else you think this could be implemented.</p>
</section>

<section id="related-reading">
  <h2>Related Reading <a href="#related-reading" class="permalink">#</a></h2>
  
  <ul>
    <li><a href="http://blog.whatwg.org/the-road-to-html-5-contenteditable#what">What is <code>contenteditable</code>?</a></li>
    <li><a href="http://css-tricks.com/expanding-images-html5/">Expanding Images Using HTML5’s <code>contenteditable</code></a></li>
  </ul>
</section><div id="crp_related"><h3>Related Posts:</h3><ul class="related"><li><a href="http://html5doctor.com/native-drag-and-drop/" rel="bookmark" class="crp_title">Native Drag and Drop</a></li><li><a href="http://html5doctor.com/the-output-element/" rel="bookmark" class="crp_title">The output element</a></li><li><a href="http://html5doctor.com/the-scoped-attribute/" rel="bookmark" class="crp_title">The scoped attribute</a></li><li><a href="http://html5doctor.com/why-designers-should-care-about-html5/" rel="bookmark" class="crp_title">Why designers should care about HTML5</a></li><li><a href="http://html5doctor.com/finding-your-position-with-geolocation/" rel="bookmark" class="crp_title">Finding your position with Geolocation</a></li></ul></div><p><a href="http://html5doctor.com/the-contenteditable-attribute/" rel="bookmark">The contenteditable attribute</a> originally appeared on <a href="http://html5doctor.com">HTML5 Doctor</a> on January 10, 2012.</p>
]]></content:encoded>
			<wfw:commentRss>http://html5doctor.com/the-contenteditable-attribute/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>The output element</title>
		<link>http://html5doctor.com/the-output-element/</link>
		<comments>http://html5doctor.com/the-output-element/#comments</comments>
		<pubDate>Tue, 20 Dec 2011 14:30:20 +0000</pubDate>
		<dc:creator>Richard Clark</dc:creator>
				<category><![CDATA[Elements]]></category>
		<category><![CDATA[HTML 5]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[output]]></category>

		<guid isPermaLink="false">http://html5doctor.com/?p=3976</guid>
		<description><![CDATA[<p>Across the web, you’ll see a range of sites that feature calculators for working out things like loan repayments, mortgage rates, tax, insurance, and more. Until now, we’ve had no way of semantically marking up the result of those calculations. Enter: the <code>&#60;output&#62;</code> element! In this article, we’ll show you <code>&#60;output&#62;</code> and some related JavaScript tricks. Let’s get cracking.</p> ]]></description>
			<content:encoded><![CDATA[<p>Across the web, you’ll see a range of sites that feature calculators for working out things like loan repayments, mortgage rates, tax, insurance, and more. Until now, we’ve had no way of semantically marking up the result of those calculations. Enter: the <code>&lt;output&gt;</code> element! In this article, we’ll show you <code>&lt;output&gt;</code> and some related JavaScript tricks. Let’s get cracking.</p> 

<section id="definition">
  <h2>The Definition <a href="#definition" class="permalink">#</a></h2>
  
  <p>The <code>&lt;output&gt;</code> element, new in HTML5, is used in forms. The WHATWG HTML specification describes <code>&lt;output&gt;</code> very simply:</p>
  
  <blockquote>
    <p>The output element represents the result of a calculation.</p>
<footer>&mdash; <cite><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-button-element.html#the-output-element">WHATWG HTML specification</a></cite></footer>
</blockquote>

  <p>Along with the standard <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/elements.html#global-attributes">global attributes</a>, <code>&lt;output&gt;</code> also accepts the following:</p>
  
  <dl> 
    <dt><code>for</code></dt>
    <dd>A space-separated list containing the IDs of the elements whose values went into the calculation.</dd>
    <dt><code>form</code></dt>
    <dd>Associates the <code>&lt;output&gt;</code> element with its <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#form-owner">form owner</a>. The value must be the ID of a form in the same document. This allows you to place an <code>&lt;output&gt;</code> element outside of the <code>&lt;form&gt;</code> with which it is associated.</dd>
    <dt><code>name</code></dt>
    <dd>The name of the element.</dd>
  </dl>
</section>

<section id="implementation">
  <h2>Implementing <code>&lt;output&gt;</code> <a href="#implementation" class="permalink">#</a></h2>
  
  <p>We’ll start by creating a simple example that adds two whole numbers together (Figure 1). We’ll use the new-in-HTML5 <code>number</code> input type and the <code>parseInt</code> JavaScript function to convert the input strings to integers:</p>
  
  <figure>
    <pre><code>&lt;form onsubmit="return false" oninput="o.value = parseInt(a.value) + parseInt(b.value)"&gt;
  &lt;input name="a" type="number" step="any"&gt; +
  &lt;input name="b" type="number" step="any"&gt; =
  <mark>&lt;output name="o"&gt;&lt;/output&gt;</mark>
&lt;/form&gt;</code></pre>
  
    <img src="http://html5doctor.com/wp-content/uploads/2011/10/output-construction.png" alt="Construction of a calculation using the output element" />
  
    <figcaption>Figure 1: A simple calculator, rendered in Chrome</figcaption>
  </figure>
  
  <aside class="sidenote">
    <p><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/common-input-element-attributes.html#the-step-attribute">The <code>step</code> attribute</a> is new to HTML5. It defines the increment by which a <code>number</code> input increases and decreases.</p>
  </aside>    
  
  <div class="callout highlight-block">
    <p>Notice that we’re using the now-standard <code>oninput</code> event, which has replaced the <a href="http://www.w3.org/Bugs/Public/show_bug.cgi?id=11129">deprecated <code>onforminput</code> event</a>. Daniel Friesen has written a detailed article on <a href="http://blog.danielfriesen.name/2010/02/16/html5-browser-maze-oninput-support/">the background and current support of <code>oninput</code></a>. <code>oninput</code> isn’t supported in IE8 and below, and its IE9 support is a little flaky, but you can work around these problems using <a href="http://www.useragentman.com/blog/2011/05/12/fixing-oninput-in-ie9-using-html5widgets/">the html5Widgets polyfill</a>.</p>
  </div>
  
  <p><a href="http://html5doctor.com/demos/output/1.html">See a live example of the code in Figure 1.</a></p>
  
  <p>As you’d expect, if you only enter a single value, the function returns <abbr title="Not a Number">NaN</abbr>. It’s effectively trying to add a number and an undefined value, and 1 + undefined = undefined.</p>
  
  <section id="for-attribute">
    <h3>Using the <code>for</code> Attribute <a href="#for-attribute" class="permalink">#</a></h3>
    
    <p>Let’s build on the previous example and add the <code>for</code> attribute to the <code>&lt;output&gt;</code> (Figure 2). We need to add IDs to each of the associated <code>&lt;input&gt;</code>s, just as we would with the <code>for</code> attribute on a <code>&lt;label&gt;</code>:</p>
    
    <figure>
      <pre><code>&lt;form onsubmit="return false" oninput="o.value = parseInt(a.value) + parseInt(b.value)"&gt;
  &lt;input name="a" id="a" type="number" step="any"&gt; +
  &lt;input name="b" id="b" type="number" step="any"&gt; =
  &lt;output name="o" <mark>for="a b"</mark>&gt;&lt;/output&gt;
&lt;/form&gt;</code></pre>

      <figcaption>Figure 2: Using the <code>for</code> attribute on the <code>&lt;output&gt;</code> element</figcaption>
    </figure>

    <p><a href="http://html5doctor.com/demos/output/2.html">See a live example of the code in Figure 2.</a></p>
  </section>
  
  <section id="valueAsNumber">
    <h3>The <code>valueAsNumber</code> Property <a href="#valueAsNumber" class="permalink">#</a></h3>
    
    <p>HTML5 has also introduced the <code>valueAsNumber</code> property of JavaScript input objects (specifically those of type number, date, and range). This returns the value as a number rather than as a string, meaning we no longer need to use <code>parseInt</code> or <code>parseFloat</code>, and the <code>+</code> operator adds rather than concatenates:</p>
    
    <figure>
      <pre><code>&lt;form onsubmit="return false" <mark>oninput="o.value = a.valueAsNumber + b.valueAsNumber"</mark>&gt;
  &lt;input name="a" id="a" type="number" step="any"&gt; +
  &lt;input name="b" id="b" type="number" step="any"&gt; =
  &lt;output name="o" for="a b"&gt;&lt;/output&gt;
&lt;/form&gt;</code></pre>

      <figcaption>Figure 3: Using the <code>valueAsNumber</code> property for retrieving a numeric value from an input</figcaption>
    </figure>

    <p><a href="http://html5doctor.com/demos/output/3.html">See a live example of the code in Figure 3.</a></p>
  </section>
</section>

<section id="invoicing-calculator">
  <h2>Invoicing Calculator: An In-depth Example with Fallbacks <a href="#invoicing-calculator" class="permalink">#</a></h2>
  
  <p>For a more realistic example, let’s create an invoicing calculator that multiplies the number of hours by the hourly rate and adds tax to give an overall total (Figure 4):</p>
  
  <figure>
    <pre><code>&lt;form onsubmit="return false" oninput="amount.value = (hours.valueAsNumber * rate.valueAsNumber) + ((hours.valueAsNumber * rate.valueAsNumber) * vat.valueAsNumber)"&gt;
  &lt;legend&gt;Invoice&lt;/legend&gt;

  &lt;p&gt;&lt;label for="hours"&gt;Number of hours&lt;/label&gt;
  &lt;input type="number" min="0" id="hours" name="hours"&gt;&lt;/p&gt;

  &lt;p&gt;&lt;label for="rate"&gt;Rate&lt;/label&gt;
  &lt;span&gt;&pound;&lt;/span&gt;&lt;input type="number" min="0" id="rate" name="rate"&gt;&lt;/p&gt;

  &lt;p&gt;&lt;label for="vat"&gt;VAT&lt;/label&gt;
  &lt;input type="number" min="0" id="vat" value="0.20" name="vat"&gt;&lt;/p&gt;

  &lt;p&gt;Total: &lt;strong&gt;&pound;&lt;output name="amount" for="hours rate vat"&gt;0&lt;/output&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;/form&gt;</code></pre>

    <img src="http://html5doctor.com/wp-content/uploads/2011/10/invoice-calc.png" alt="Invoice tax calculator using the output element" />

    <figcaption>Figure 4: An invoicing calculator that renders its result in an <code>output</code> element</figcaption>
  </figure>

  <p><a href="http://html5doctor.com/demos/output/4.html">See a live example of the code in Figure 4.</a></p>
  
  <p>Nothing too complicated going on there. In fact, the scripting is so simple that even I can do it <img src='http://html5doctor.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
</section>

<section id="input-range">
  <h2>A Mildly Controversial Example Using <code>&lt;input type="range"&gt;</code> <a href="#input-range" class="permalink">#</a></h2>
  
  <p>HTML5 also introduces the <code>range</code> input type, which renders as a slider control in supporting browsers. With this input type, a user can enter an approximate value within a given range without having to be completely precise or directly type a numeric value. For cross browser compatibility, see <a href="http://remysharp.com/2011/07/18/input-range-polyfill/">Remy’s input range polyfill</a>.</p>
  
  <p>While researching this article, I found a number of examples using the <code>&lt;output&gt;</code> element in conjunction with <code>&lt;input type="range"&gt;</code> as shown in Figure 5:</p>
  
  <figure>
    <pre><code>&lt;form onsubmit="return false" oninput="level.value = flevel.valueAsNumber"&gt;
  &lt;label for="flying"&gt;Flying Skill Level&lt;/label&gt;
  &lt;input name="flevel" id="flying" type="range" min="0" max="100" value="0"&gt; 
  &lt;output for="flying" name="level"&gt;0&lt;/output&gt;/100
&lt;/form&gt;</code></pre>

    <img src="http://html5doctor.com/wp-content/uploads/2011/10/output-range.png" alt="Output example using type=range" />

    <figcaption>Figure 5: Using <code>&lt;input type="range"&gt;</code> with the <code>&lt;output&gt;</code> element</figcaption>
  </figure>
  
  <p><a href="http://html5doctor.com/demos/output/5.html">See a live example of the code in Figure 5.</a></p>
  
  <p>Using <code>&lt;output&gt;</code> to show the current value to the user seems like a perfectly reasonable use case to me, but it isn’t <q cite="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-button-element.html#the-output-element">the result of a calculation</q> as the spec describes. I haven’t spoken directly to Hixie about this, but a couple of people on the IRC channel seemed to agree with, so I filed a <a href="http://www.w3.org/Bugs/Public/show_bug.cgi?id=14379">bug report</a> to request the definition be amended. I’ll update this article if something changes.</p>
</section>  

<section id="support">
  <h2>Browser Support and Polyfills <a href="#support" class="permalink">#</a></h2>
  
  <p>The good news is that all modern browsers support the <code>&lt;output&gt;</code> element to some extent. The bad news is that there are still a few gotchas.</p>
  
  <table class="wide">
    <caption>Browser support for the <code>&lt;output&gt;</code> element</caption>
    <thead>
      <tr>
        <th scope="col">Browser</th>
        <th scope="col">Support</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th scope="row">Chrome</th>
        <td>13+</td>
      </tr>
      <tr>
        <th scope="row">Safari</th>
        <td>5.1+</td>
      </tr>
      <tr>
        <th scope="row">Firefox*</th>
        <td>6+</td>
      </tr>
      <tr>
        <th scope="row">Opera</th>
        <td>9.20+</td>
      </tr>
      <tr>
        <th scope="row">Internet Explorer</th>
        <td>10+</td>
      </tr>
    </tbody>
  </table>
  
  <p><small>* Firefox does support the <code>&lt;output&gt;</code> element and the <code>oninput</code> event, but <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=636737">it doesn’t support the <code>valueAsNumber</code> property</a>.</small></p>
  
  <p>All the examples we’ve seen so far should work perfectly in Opera 11.5+, Safari 5.1+, and Chrome 13+. IE, as you might expect, is lagging somewhat, but support for <code>&lt;output&gt;</code> is in IE10 Platform Preview 2, and support for <code>oninput</code> is already in IE9.</p>
  
  <p>In order to work around this in our simple examples, we’ll need to revert to the tried-and-trusted <code>getElementByID</code> and <code>parseFloat</code> (Figure 6):</p>
  
  <figure>
    <pre><code>&lt;form onsubmit="return false" <mark>oninput="document.getElementById('o').innerHTML = parseFloat(document.getElementById('a').value) + parseFloat(document.getElementById('b').value)"</mark>&gt;
  &lt;input name="a" id="a" type="number" step="any"&gt; +
  &lt;input name="b" id="b" type="number" step="any"&gt; =
  &lt;output name="o" id="o" for="a b"&gt;&lt;/output&gt;
&lt;/form&gt;</code></pre>

    <figcaption>Figure 6: Using <code>getElementById</code> to support older browsers</figcaption>
  </figure>

  <p><a href="http://html5doctor.com/demos/output/6.html">See a live example of the code in Figure 6.</a></p>

  <p>While this isn’t ideal, it’s workable until those less-capable browsers die a slow and painful death. Alternatively, you can use polyfills to plug the gaps.</p>
  
  <p>To check support in your current browser, <a href="http://miketaylr.com/code/html5-output-element-support.html">open up Mike Taylor’s support test page</a>.
  
  <section id="polyfills">
    <h3>Polyfills <a href="#polyfills" class="permalink">#</a></h3>
    
    <p>To support less-capable browsers, there are polyfills such as <a href="https://github.com/zoltan-dulac/html5Widgets">HTML5 Widgets</a> created by <cite><a href="http://www.useragentman.com">Zoltan &#8220;Du Lac&#8221; Hawryluk</a></cite>. Zoltan talks you through the process in <a href="http://www.useragentman.com/blog/2010/07/27/cross-browser-html5-forms-using-modernizr-webforms2-and-html5widgets/">this detailed article on creating cross browser forms using html5Widgets</a>.</p>
  </section>
</section>

<section id="summary">
  <h2>Summary <a href="#summary" class="permalink">#</a></h2>
  
  <p>You probably won&#8217;t find yourself using the <code>&lt;output&gt;</code> element all the time, but it’s useful in a whole host of situations. Calculating values on financial sites spring to mind, or outputting the current mouse position, or perhaps the goal difference in a table of sports teams. What other use cases can you think of for <code>&lt;output&gt;</code>? Let us know in the comments!</p>
</section>

<section id="links">
  <h2>Related reading <a href="#links" class="permalink">#</a></h2>
  
  <ul>
    <li><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-button-element.html#the-output-element">WHATWG HTML Specification for <code>&lt;output&gt;</code></a></li>
    <li><a href="http://www.w3.org/wiki/HTML/Elements/output">W3C Elements Wiki Page for <code>&lt;output&gt;</code></a></li>
    <li><a href="http://wufoo.com/html5/elements/3-output.html">Wufoo HTML5 Forms Tests for <code>&lt;output&gt;</code></a></li>
    <li><a href="https://developer.mozilla.org/en/HTML/Element/output">Mozilla Developer Network docs on <code>&lt;output&gt;</code></a></li>
    <li><a href="http://www.useragentman.com/blog/2011/05/10/is-onforminput-deprecated-in-html5-forms-and-why-should-i-care-anyways/">Is <code>onforminput</code> Deprecated in HTML5 Forms? (And Why Should I Care Anyways?) by <cite>Zoltan Hawryluk</cite></a></li>
    <li><a href="http://blog.danielfriesen.name/2010/02/16/html5-browser-maze-oninput-support/">A HTML5 Browser Maze: <code>oninput</code> Support by <cite>Daniel Friessen</cite></a></li>
    <li><a href="http://www.useragentman.com/blog/2011/05/12/fixing-oninput-in-ie9-using-html5widgets/">Fixing <code>oninput</code> in IE Using html5Widgets by <cite>Zoltan Hawryluk</cite></a></li>
  </ul>
</section><div id="crp_related"><h3>Related Posts:</h3><ul class="related"><li><a href="http://html5doctor.com/the-details-and-summary-elements/" rel="bookmark" class="crp_title">The details and summary elements</a></li><li><a href="http://html5doctor.com/the-contenteditable-attribute/" rel="bookmark" class="crp_title">The contenteditable attribute</a></li><li><a href="http://html5doctor.com/how-to-get-all-the-browsers-playing-ball/" rel="bookmark" class="crp_title">How to get all the browsers playing ball</a></li><li><a href="http://html5doctor.com/video-subtitling-and-webvtt/" rel="bookmark" class="crp_title">Video Subtitling and WebVTT</a></li><li><a href="http://html5doctor.com/your-questions-answered-11/" rel="bookmark" class="crp_title">Your Questions Answered #11</a></li></ul></div><p><a href="http://html5doctor.com/the-output-element/" rel="bookmark">The output element</a> originally appeared on <a href="http://html5doctor.com">HTML5 Doctor</a> on December 20, 2011.</p>
]]></content:encoded>
			<wfw:commentRss>http://html5doctor.com/the-output-element/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Video Subtitling and WebVTT</title>
		<link>http://html5doctor.com/video-subtitling-and-webvtt/</link>
		<comments>http://html5doctor.com/video-subtitling-and-webvtt/#comments</comments>
		<pubDate>Tue, 29 Nov 2011 15:33:59 +0000</pubDate>
		<dc:creator>Tom Leadbetter</dc:creator>
				<category><![CDATA[Accessibility]]></category>
		<category><![CDATA[Elements]]></category>
		<category><![CDATA[multimedia]]></category>
		<category><![CDATA[HTML 5]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[subtitles]]></category>
		<category><![CDATA[video]]></category>
		<category><![CDATA[webvtt]]></category>

		<guid isPermaLink="false">http://html5doctor.com/?p=4084</guid>
		<description><![CDATA[<p>We’ve been able to play video in the browser without a plugin for a couple of years now, and whilst there are still some codec annoyances, things appear to have settled down on the video front. The next step is adding resources to the video to make it more accessible and provide more options to the viewer.</p>]]></description>
			<content:encoded><![CDATA[<p>We’ve been able to play video in the browser without a plugin for a couple of years now, and whilst there are still some codec annoyances, things appear to have settled down on the video front. The next step is adding resources to the video to make it more accessible and provide more options to the viewer.</p>
<p>We currently have no means to provide information about what’s happening or being said in the video, which means the video isn’t very accessible and the user can’t easily navigate to a particular section of the video. Thankfully, there’s a new format specification in the works called <a href="http://www.whatwg.org/specs/web-apps/current-work/webvtt.html">WebVTT (Web Video Text Tracks)</a>. As of now, it’s only in the WHATWG spec, but the recently established <a href="http://www.w3.org/community/texttracks/">W3C Web Media Text Tracks Community Group</a> should introduce a WebVTT spec to the W3C soon.</p>
<p class="callout">You may recall a similar format called WebSRT (Web Subtitle Resource Tracks) that was recently under discussion. WebSRT was renamed to, and has been replaced by, WebVTT.</p>
<p>A WebVTT (.vtt) file is simply plain text containing several types of information about the video:</p>
<dl>
<dt>Subtitles</dt>
<dd>The transcription or translation of the dialogue.</dd>
<dt>Captions</dt>
<dd>Similar to subtitles, but may also include sound effects and other audio information.</dd>
<dt>Descriptions</dt>
<dd>Intended to be a separate text file that describes the video through a screenreader.</dd>
<dt>Chapters</dt>
<dd>Intended to help the user navigate through the video.</dd>
<dt>Metadata</dt>
<dd>Information and content about the video, which isn’t intended to be displayed to the viewer by default, though you may wish to do so using JavaScript.</dd>
</dl>
<p>This article will mostly be talking about <a href="#contents">subtitles and captions</a>, but it will briefly touch on <a href="#chapters">chapters</a> too.</p>
<p class="callout">Beyond the scope of this article but worth mentioning is the <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#text-track-api">text track API</a>, which, amongst other things, denotes how many text tracks there are and which ones have loaded and are ready for use. If you have used this API, <a href="http://html5doctor.com/ask-the-doctor/">let us know</a>.</p>
<section id="how">
<h2>How to Make and Link to a WebVTT file <a href="#how" class="permalink">#</a></h2>
<p>All you need to make a WebVTT file is a simple text editor. Type <code>WEBVTT</code> as the first line of the file and save it as a .vtt file. In the future, we expect existing captioning tools such as <a href="http://www.universalsubtitles.org/">Universal Subtitles</a> to export to WebVTT format.</p>
<figure>
<pre><code>WEBVTT</code></pre>
<figcaption>The simplest possible valid WebVTT file</figcaption>
</figure>
<p>That’s all you need to get started. Next, we have to link to the file in the HTML document. We do this via the <a href="http://html5doctor.com/video-the-track-element-and-webm-codec/"><code>&lt;track&gt;</code> element</a>, which is a child of the video element. The <code>&lt;track&gt;</code> element has several optional attributes:</p>
<ul>
<li>the source WebVTT file (<code>src</code>),</li>
<li>the language of the track (<code>srclang</code>),</li>
<li>a user-readable <code>label</code>, and</li>
<li>what <code>kind</code> of track it is. The values of the <code>kind</code> attribute come from the list above (i.e., <code>subtitles</code>, <code>captions</code>, etc.).</li>
</ul>
<p>In the following example, we’re using a <code>&lt;track&gt;</code> element for subtitles:</p>
<pre><code>&lt;video width=&quot;640&quot; height=&quot;480&quot; controls&gt;
  &lt;source src=&quot;video.mp4&quot; type=&quot;video/mp4&quot; /&gt;
  &lt;source src=&quot;video.webm&quot; type=&quot;video/webm&quot; /&gt;
  &lt;track src=&quot;subtitles.vtt&quot; kind=&quot;subtitles&quot; srclang=&quot;en&quot; label=&quot;English&quot; /&gt;
  &lt;!-- fallback for rubbish browsers --&gt;
&lt;/video&gt;</code></pre>
<p>A few notes about the attributes:</p>
<ul>
<li>If no <code>kind</code> is specified, the default is <code>subtitles</code>.</li>
<li>If the <code>kind</code> is <code>subtitles</code>, then <code>srclang</code> is required.</li>
<li>There should not be two tracks of the same <code>kind</code> with the same <code>label</code>.</li>
</ul>
<p>In the above example, we use a <code>&lt;video&gt;</code> element with two different <code>&lt;src&gt;</code> elements (for cross-browser loveliness). After the sources comes the <code>&lt;track&gt;</code> element. You can have several <code>&lt;track&gt;</code> elements as you might have subtitles, captions, and descriptions all in different languages.</p>
<p class="callout"><code>&lt;track&gt;</code> doesn’t presuppose a particular file format. <a href="http://html5labs.interoperabilitybridges.com/prototypes/video-captioning/video-captioning/info">Microsoft supports</a> the <a href="http://www.w3.org/TR/ttaf1-dfxp/"><abbr title="Timed Text Markup Language">TTML</abbr></a> format, but this format will not be implemented by other browser vendors.</p>
</section>
<section id="contents">
<h2>WebVTT Contents <a href="#contents" class="permalink">#</a></h2>
<p>We now know how to make a WebVTT file and how to reference it in an HTML document, but what goes inside it? Within the file, we list what are known as “cues”. The WebVTT file might only have one cue, but it can contain as many as you want. Each cue starts with an ID, followed by the time settings, followed by the text. Each cue is separated by a blank line. Here’s an example of captions:</p>
<figure>
<pre><code>WEBVTT

1
00:00:01.000 --&gt; 00:00:10.000
This is the first line of text, displaying from 1-10 seconds

2
00:00:15.000 --&gt; 00:00:20.000
And the second line of text
separated over two lines</code></pre>
<figcaption>WebVTT example content</figcaption>
</figure>
<p>The above example has two cues. Times must be written in <code>hh:mm:ss.mmm</code> format, so the timings in this example occur in the first twenty seconds. The second cue will split the text over two lines automatically.</p>
<p>If you have a segment of text that needs to appear in a karaoke/paint-on caption style, then you can place timers inline with text:</p>
<figure>
<pre><code>1
00:00:01.000 --&gt; 00:00:10.000
Never gonna give you up &lt;00:00:01.000&gt; Never gonna let you down &lt;00:00:05.000&gt; Never gonna run around and desert you</code></pre>
<figcaption>Karaoke-style captioning</figcaption>
</figure>
</section>
<section id="styling">
<h2>Styling Options <a href="#styling" class="permalink">#</a></h2>
<p>The previous examples specify the minimum configuration you need for subtitling and captioning, but you can style your captions too. Let’s start with the cue settings, which are done on the same line as the time settings:</p>
<dl>
<dt><code>D:vertical / D:vertical-lr</code></dt>
<dd>Display the text vertically rather than horizontally. This also specifies whether the text grows to the left (<code>vertical</code>) or to the right (<code>vertical-lr</code>).</dd>
<dt><code>L:X / L:X%</code></dt>
<dd>Either a number or a percentage. If a percentage, then it is the position from the top of the frame. If a number, this represents what line number it will be.</dd>
<dt><code>T:X%</code></dt>
<dd>The position of the text horizontally on the video. <code>T:100%</code> would place the text on the right side of the video.</dd>
<dt><code>A:start / A:middle / A:end</code></dt>
<dd>The alignment of the text within its box – <code>start</code> is left-aligned, <code>middle</code> is centre-aligned, and <code>end</code> is right-aligned.</dd>
<dt><code>S:X%</code></dt>
<dd>The width of the text box as a percentage of the video width.</dd>
</dl>
<p>To make use of these settings, put them alongside the time settings, like this:</p>
<pre><code>00:00:01.000 --&gt; 00:00:10.000 A:middle T:50%
00:00:01.000 --&gt; 00:00:10.000 A:end D:vertical
00:00:01.000 --&gt; 00:00:10.000 A:start T:100% L:0%</code></pre>
<p>which would result in something like the following:</p>
<figure>
    <img src="http://html5doctor.com/wp-content/uploads/2011/11/video-subtitles-demo1.png" alt="Examples of subtitle display" width="354" height="109" /></p>
<figcaption>Examples of subtitle display and alignment</figcaption>
</figure>
<p>Along with the above cue settings, you can use inline styles for text:</p>
<dl>
<dt>Bold text</dt>
<dd><code>&lt;b&gt;Lorem ipsum&lt;/b&gt;</code></dd>
<dt>Italic text</dt>
<dd><code>&lt;i&gt;dolor sit amet&lt;/i&gt;</code></dd>
<dt>Underlined text</dt>
<dd><code>&lt;u&gt;consectetuer adipiscing&lt;/u&gt;</code></dd>
<dt>Ruby text</dt>
<dd><code>&lt;ruby&gt;見&lt;rt&gt;み&lt;/rt&gt;&lt;/ruby&gt;</code></dd>
</dl>
<p>You can even apply a CSS class to a section of text using <code>&lt;c.myClass&gt;Lorem ipsum&lt;/c&gt;</code>, giving us many more styling options.</p>
<p>Finally, you can add a declaration representing the name of the voice: <code>&lt;v Tom&gt;Hello world&lt;/v&gt;</code>. This declaration accomplishes three things:</p>
<ol>
<li>The caption will display the voice (Tom) in addition to the caption text.</li>
<li>The name of the voice can be read by a screenreader, possibly event using a different voice for male or female names.</li>
<li>It offers a hook for styling so that, for example, all captions for Tom could be in blue.</li>
</ol>
<section id="chapters">
<h3>Chapters</h3>
<p>You can provide a chapter list for the video the same way you would provide subtitles or captions. Start with the same <code>WEBVTT</code> declaration, and then for each cue, declare the chapter number, the start and stop times, and the chapter title:</p>
<figure>
<pre><code>&lt;track src=&quot;chapters.vtt&quot; kind=&quot;chapters&quot; srclang=&quot;en&quot; /&gt;</code></pre>
<figcaption>HTML <code>&lt;track&gt;</code> element for providing chapters to a video</figcaption>
</figure>
<figure>
<pre><code>WEBVTT

Chapter 1
00:00:01.000 --&gt; 00:00:10.000>
Introduction to HTML5</code></pre>
<figcaption>WebVTT file containing video chapter markers</figcaption>
</figure>
</section>
</section>
<section id="browsers">
<h2>Browser Support <a href="#browsers" class="permalink">#</a></h2>
<p>One slight glitch with WebVTT: not a single browser currently supports it. All major browsers have started working on implementations, so we should see some results soon. Thankfully, in the meantime, there are several JavaScript polyfills available:</p>
<ul>
<li><a href="http://www.storiesinflight.com/js_videosub/">js_videosub</a></li>
<li><a href="http://www.delphiki.com/html5/playr/">Playr</a></li>
<li><a href="http://mediaelementjs.com/">MediaElementJS</a></li>
<li><a href="http://dev.mennerich.name/showroom/html5_video/">LeanBack player</a> (and upcoming <a href="http://leanbackplayer.com/test/webvtt.html">new version</a>)</li>
<li><a href="https://github.com/cgiffard/Captionator">Captionator</a>&nbsp;</li>
</ul>
</section>
<section id="demo">
<h2>Demo <a href="#demo" class="permalink">#</a></h2>
<p>We&#8217;ve put together a <a href="http://html5doctor.com/demos/webvtt/">quick demo</a> which uses the <a href="http://www.delphiki.com/html5/playr/">Playr</a> polyfill. We started using <a href="http://mediaelementjs.com/">MediaElementJS</a>, but it doesn’t sport as many features as <a href="http://www.delphiki.com/html5/playr/">Playr</a>, such as separate lines of text and CSS classes. In the <a href="http://html5doctor.com/demos/webvtt/">demo</a>, the subtitles start at 2 seconds and 15 seconds and use bold, underline, and custom styles. Here’s the <a href="http://html5doctor.com/demos/webvtt/subtitles.vtt">associated WebVTT file</a>.</p>
</section>
<section id="conclusion">
<h2>Conclusion <a href="#conclusion" class="permalink">#</a></h2>
<p>This article covers the basics of creating a WebVTT file suitable for subtitles or captions for a video. We know how to add cues and chapters and how to add styles and change how the text appears on the video. Although no browser yet supports it, there’s a lot more to come for accessible video, so stay tuned to the <a href="http://www.w3.org/community/texttracks/">W3C Web Media Text Tracks Community Group</a>.</p>
<p>What are your thoughts on WebVTT? Are any of you using it now? How can it be improved?</p>
<p>Finally, let’s thank <a href="http://twitter.com/#!/silviapfeiffer">@silviapfeiffer</a> for taking the time to answer some questions about WebVTT and for her tremendous work in this field.</p>
</section>
<section id="reading">
<h2>Reading <a href="#reading" class="permalink">#</a></h2>
<ul>
<li>Follow <a href="http://twitter.com/#!/silviapfeiffer">@silviapfeiffer</a></li>
<li><a href="http://www.w3.org/community/texttracks/">W3C Web Media Text Tracks Community Group</a></li>
<li><a href="http://blog.gingertech.net/2011/06/27/recent-developments-around-webvtt/">Recent developments around WebVTT</a></li>
<li><a href="http://html5videoguide.net/presentations/WebVTT/">Presentation: HTML5 video accessibility and the WebVTT file format</a></li>
<li><a href="http://www.youtube.com/watch?v=gK72pcu3cpk">HTML5 video accessibility and the WebVTT file format &#8211; Audio Described</a></li>
<li><a href="http://leanbackplayer.com/other/webvtt.html">A review with notes and thoughts for LeanBack Player</a></li>
<li><a href="http://quuz.org/webvtt/">WebVTT validator</a></li>
<li><a href="http://www.iandevlin.com/blog/2011/05/html5/webvtt-and-video-subtitles">WebVTT and Video Subtitles</a></li>
<li><a href="http://www.openmediadevelopers.org/pmwiki.php/Main/OVC2011VidA11y">The Open Video Alliance</a></li>
<li><a href="http://www.delphiki.com/webvtt/">Understanding WebVTT file format (draft)</a></li>
<li><a href="http://scottbw.wordpress.com/2011/06/28/creating-subtitles-and-audio-descriptions-with-html5-video/">Creating subtitles and audio descriptions with HTML5 video</a></li>
</ul>
</section>
<div id="crp_related">
<h3>Related Posts:</h3>
<ul class="related">
<li><a href="http://html5doctor.com/video-the-track-element-and-webm-codec/" rel="bookmark" class="crp_title">Video: the track element and webM codec</a></li>
<li><a href="http://html5doctor.com/the-video-element/" rel="bookmark" class="crp_title">The video element</a></li>
<li><a href="http://html5doctor.com/html5-simplequiz-4-figures-captions-and-alt-text/" rel="bookmark" class="crp_title">HTML5 Simplequiz #4: figures, captions and alt text</a></li>
<li><a href="http://html5doctor.com/your-questions-answered-8/" rel="bookmark" class="crp_title">Your Questions Answered #8</a></li>
<li><a href="http://html5doctor.com/html5-for-web-developers/" rel="bookmark" class="crp_title">HTML5 for Web Developers</a></li>
</ul>
</div>
<p><a href="http://html5doctor.com/video-subtitling-and-webvtt/" rel="bookmark">Video Subtitling and WebVTT</a> originally appeared on <a href="http://html5doctor.com">HTML5 Doctor</a> on November 29, 2011.</p>
]]></content:encoded>
			<wfw:commentRss>http://html5doctor.com/video-subtitling-and-webvtt/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Pushing and Popping with the History API</title>
		<link>http://html5doctor.com/history-api/</link>
		<comments>http://html5doctor.com/history-api/#comments</comments>
		<pubDate>Tue, 15 Nov 2011 13:09:47 +0000</pubDate>
		<dc:creator>Mike Robinson</dc:creator>
				<category><![CDATA[JavaScript APIs]]></category>
		<category><![CDATA[api]]></category>
		<category><![CDATA[history]]></category>
		<category><![CDATA[HTML 5]]></category>
		<category><![CDATA[html5]]></category>

		<guid isPermaLink="false">http://html5doctor.com/?p=3897</guid>
		<description><![CDATA[Until recently, we developers couldn’t to do much with the state and history of the browser. We could check the number of items in the history and push users forwards and backwards, but this provides little benefit to the user. With the rise of more dynamic web pages, we need more control. Thankfully, HTML5 gives [...]]]></description>
			<content:encoded><![CDATA[<p>Until recently, we developers couldn’t to do much with the state and history of the browser. We could check the number of items in the history and push users forwards and backwards, but this provides little benefit to the user. With the rise of more dynamic web pages, we need more control. Thankfully, HTML5 gives us that control by extending the JavaScript History API.</p>
<section id="the-point">
<h2>What’s the point? <a class="permalink" href="#the-point">#</a></h2>
<p>It goes without saying that URLs are important. They’re <em>the</em> method of accessing the vast collections of information and resources on the web, and more recently, they’ve begun representing the intended state of a web application. You can copy these URLs and share them with your friends or use them to create links from any HTML document. They’re the veins of the web, and they need to be looked after.</p>
<p>Previously, the JavaScript History API offered some very simple functionality:</p>
<pre><code>// Check the length of the history stack
console.log(history.length);

// Send the user agent forward
console.log(history.forward());

// Send the user agent back
console.log(history.back());

// Send the user agent back (negative) or forward (positive)
// by a given number of items
console.log(history.go(-3));
</code></pre>
<p>With dynamic Ajax web applications, where the browser updates the page in parts instead of changing location entirely, it’s difficult to give the user a URL to bookmark or share the current application state. <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/elements.html#the-id-attribute">Fragment identifiers</a>, like those used on this article’s headings via the <code>id</code> attribute, provide some state information, but they’re entirely dependent on client-side scripts.</p>
<p>The changes to the <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html">History API</a> are intended to give developers ways to push history items to the browser so the native back and forward actions can cycle through those items. These history items can also hold data that you can later extract to restore the page state.</p>
<blockquote>
<p>Pages can <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html#dom-history-pushstate" title="dom-history-pushState">add</a> <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html#state-object" title="state object">state objects</a> between their entry in the session history and the next (“forward”) entry. These are then <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html#event-popstate" title="event-popstate">returned to the script</a> when the user (or script) goes back in the history, thus enabling authors to use the “navigation” metaphor even in one-page applications.</p>
<footer>- <cite><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html" title="6.4 Session history and navigation">WHATWG</a></cite></footer>
</blockquote>
<p>If the user copies or bookmarks a stateful URL and visits it later, your back-end can be configured to interpret such a URL and jump the user right to the correct page and/or state.</p>
<p>In this article, I’ll cover the client-side use of the History API, so make sure you set up your server to work with the new URLs. If you’ve already built an accessible website that provide these entry points, you’re laughing!</p>
<section id="those-fking-hashbangs">
<h4>Those <em>f#!king</em> hashbangs… <a class="permalink" href="#those-fking-hashbangs">#</a></h4>
<p>You may have already seen articles fussing over the adoption of the “hashbang” (#!) pattern on sites like <a href="http://twitter.com">Twitter</a>. This technique updates the address bar with a fragment identifier that can then be used by JavaScript to determine which page and state should be displayed.</p>
<p>This works as a method of creating a bookmarkable, shareable URL for a page’s state in the absense of a standard API. While the Twitter implementation accepts both <code>http://twitter.com/#!/akamike</code> and <code>http://twitter.com/akamike</code>, it has some disadvantages:</p>
<ul>
<li>The fragment identifier is only accessible on the client side. This means that only JavaScript can utilise it, so browsers without JavaScript enabled are out of luck.</li>
<li>As the server does not receive the path following the hashbang, removing that JavaScript drops support for all those URLs. That’s a lot of broken links, so you’re stuck with that JavaScript <em>forever</em>.</li>
<li>It’s ugly. It’s a hack and it looks like one.</li>
</ul>
<p>The hashbang was never intended to be a long-term solution, so don’t rely on it. If you do use hashbangs, be prepared to deal with the consequences (and possible backlash from web purists).</p>
</section>
</section>
<section id="making-history">
<h2>Making History <a class="permalink" href="#making-history">#</a></h2>
<p>These examples will build on top of each other. We’ll start with a <a href="http://html5doctor.com/wp-content/uploads/2011/10/history_base.html">basic HTML document</a> with some inline styles and scripts for your convenience.</p>
<aside class="sidenote">
<p>For a simple HTTP server, open the command line, <code>cd</code> to the directory you would like to serve, run <code>python -m SimpleHTTPServer 8080</code>, then open <code>localhost:8080</code> in your browser. Alternatively, try a bundled setup like <a href="http://www.apachefriends.org/en/xampp.html">XAMPP</a> or <a href="http://www.mamp.info/en/index.html">MAMP</a>.</p>
</aside>
<p>Save this file and open it in your favourite editor. It must be accessed via HTTP, so that means you need either a local server (e.g. <code>http://localhost/</code>) or an online web server you can upload to. <strong>Viewing the file directly using your browser’s Open File function will not work</strong>, since it uses the <code>file://</code> protocol and not HTTP. Also be sure to update the <code>href</code> attributes on each of the navigation links to ensure the correct directory structure is used. Personally, I’m viewing the demo locally at <code>http://localhost/history</code>.</p>
<p>We’ll be working exclusively within the <code>&lt;script&gt;</code> element at the end of the <code>&lt;body&gt;</code>. The code includes some simple styles and dynamically changes the content as you click the links. In reality, this could be loaded from your server via <code>XMLHttpRequest</code>, but for the purposes of this demonstration I’ve bundled it up into a self-contained file. The important part is that we have a quick-and-dirty dynamic page to work with, so let the fun begin!</p>
<p>At the moment there, is no bookmarkable URL for the different states of this page. If you click around the navigation items, then click Back in your browser, you won’t be taken back to the previous state and may even be taken away from the page to whatever you viewed before (depending on your browser). It would be nice if you could share “Socks” with your friends, right? We can do that via <code>history.pushState()</code>.</p>
<p>The <code>history.pushState()</code> method takes three parameters:</p>
<dl>
<dt><code>data</code></dt>
<dd>Some structured data, such as settings or content, assigned to the history item.</dd>
<dt><code>title</code></dt>
<dd>The name of the item in the history drop-down shown by the browser’s back and forward buttons. (Note: this is not currently supported by any major browsers.)</dd>
<dt><code>url</code> <em>(optional)</em></dt>
<dd>The URL to this state that should be displayed in the address bar.</dd>
</dl>
<p>With these parameters, you can define the state of the page, give that state a name, and even provide a bookmarkable address, as if the page had reloaded entirely. Let’s dive right in and add this to the <code>clickHandler</code> function, right above the <code>return</code> statement:</p>
<figure>
<pre><code>function clickHandler(e) {
  /* Snip... */

  // Add an item to the history log
  history.pushState(data, event.target.textContent, event.target.href);

  return event.preventDefault();
}
</code></pre>
</figure>
<p>The single line of code we added informs the <code>history</code> object that:</p>
<ul>
<li>we want to add an item to the log,</li>
<li>it should remember the data that we’ve already loaded,</li>
<li>it should assign a name to this state based on the text of the link we clicked (even though this isn’t used — it’s good to get into the habit of recording a name for the state), and</li>
<li>it should update the address bar with the <code>href</code> attribute of that link.</li>
</ul>
<p>Reload the page in your browser and click a few of the links, keeping an eye on the address bar. Notice how it changes on each click, despite the fact that you aren’t actually navigating away from this page. If you also have a look at your history log, you’ll see a long list of page titles (in this case ”Kittens!” over and over). Provided your server is set up to serve the correct page upon access, the user could copy that URL and paste it into a new browser window to jump straight to that kitten.</p>
<p>At the moment, clicking the back button will pop you through the history items, but the page won’t react to these changes. That&#8217;s because so far, we’ve only created the history records. How can we allow active users to return to a previous state? We listen to the <code>popstate</code> event.</p>
</section>
<section id="historical-events">
<h2>Historical Events in Navigation <a class="permalink" href="#historical-events">#</a></h2>
<p>The user agent fires a <code>popstate</code> event when the user navigates through their history, whether backwards or forwards, provided it isn’t taking the user away from the current page. That is, all those <code>pushState</code>s we called will keep the user on the current page, so the <code>popstate</code> event will fire for each history item they pop through.</p>
<p>Before the closing <code>&lt;/script&gt;</code> tag, add a new listener for the <code>popstate</code> event:</p>
<figure>
<pre><code>// Revert to a previously saved state
window.addEventListener('popstate', function(event) {
  console.log('popstate fired!');

  updateContent(event.state);
});
</code></pre>
</figure>
<p>We attach the event listener to the <code>window</code>, which is responsible for firing the event, and pass this event into our handler. We log a message (so we can see when this event is firing), and then we update the content using the state we saved previously. The state is attached to the <code>event</code> object via the <code>state</code> property.</p>
<p>Open up the page fresh in your browser, click around like before, and then click back. As before, the URL in the address bar changes as you cycle through states, but now the content is also restored back to what it should be. Click forward, and the content is likewise correctly restored.</p>
<div class="callout warning-block">
<p>If you look at the developer console in Chrome when you load the page for the first time, you’ll see the <code>popstate</code> event fired immediately, before you’ve even clicked a link. This is because Chrome considers the initial page load to be a change in state, and so it fires the event. In this instance, the <code>state</code> property is <code>null</code>, but thankfully the <code>updateContent</code> function deals with this. Keep this in mind when developing as it could catch you out, especially if other browsers assume this behavior.</p>
</p></div>
</section>
<section id="rewriting-history">
<h2>Rewriting history <a class="permalink" href="#rewriting-history">#</a></h2>
<p>Unfortunately, as fantastic as HTML5 is, it doesn’t allow us actual time travel. If it did, I would be going back to my childhood and telling a younger me, “Yes, you should have a slice of cake”. Take that as you will.</p>
<p>The History API does, however, allow us to make amends to our history log items. For example, we could update the current state in response to fresh user input in a form. We can do this with <code>history.replaceState</code>.</p>
<p><code>replaceState</code> works just as <code>pushState</code> does, with the exact same parameters, except that it updates the current entry instead of adding a new one. I can think of one situation in our demo where this could be used: the initial page load. If you click back for long enough, you’ll find that going back to the original URL doesn’t provide you the original content. Let’s fix that by adding the following to the bottom of our script:</p>
<figure>
<pre><code>// Store the initial content so we can revisit it later
history.replaceState({
  content: contentEl.textContent,
  photo: photoEl.src
}, document.title, document.location.href);
</code></pre>
</figure>
<p>As this runs when the page loads, it saves the initial page state. We can later load this state when the user browses back to this point via the event listener we set up previously. You can try it out by loading up the page, clicking a few links, and then hitting back until you return to the original URL. The initial content has returned!</p>
</section>
<section id="demo">
<h2>Demo <a class="permalink" href="#demo">#</a></h2>
<p>I’ve set up a demo of our completed code. I’ve also added a little back-end magic to make our <code>history.pushState</code> URLs work like a real site. Remember that the URLs you push should be live URLs that the user can bookmark and share as real entry points to your site.</p>
<p class="btn half"><a href="http://html5doctor.com/demos/history/">View the History API demo</a></p>
</section>
<section id="browser-support">
<h2>Browser support <a class="permalink" href="#browser-support">#</a></h2>
<p>Up-to-date copies of Chrome (5+), Safari (5.0+), Firefox (4.0+), and Opera (11.50+) have support for the new History API. Even some mobile browsers work just fine, like Mobile Safari on iOS 4+. Unfortunately, IE 9 and below lack support, but it <a href="http://msdn.microsoft.com/en-us/ie/hh272905.aspx#_HTML5History">should work in IE 10</a> when it arrives.</p>
<p>Safari 5.0 sometimes exhibits one oddity: navigating between states causes the loading spinner to appear and stay even when the state has been loaded. This stops when you navigate away using a link or action that does not involve a state saved by the History API.</p>
<section id="polyfill">
<h3>Polyfill <a class="permalink" href="#polyfill">#</a></h3>
<p>A polyfill does exist for the History API. The aptly named <a href="https://github.com/balupton/history.js">History.js</a> uses HTML4’s <code>hashchange</code> event with document fragment identifiers to mimic the history API in older browsers. If one of the hash URLs is used by a modern browser, it uses <code>replaceState</code> to quietly correct the URL.</p>
<p>It sounds like magic, but make sure you’re aware of the consequences of using fragment identifiers, as mentioned previously in this article. As such, the author of History.js has put together a guide titled <a href="https://github.com/balupton/history.js/wiki/Intelligent-State-Handling">Intelligent State Handling</a>.</p>
</section>
</section>
<section id="closing">
<h2>Closing thoughts <a class="permalink" href="#closing">#</a></h2>
<p>URLs go beyond just the browsing session of a user. They’re historically important markers for resources that could very well remain in use for many years to come. Before you embark on developing your site’s JavaScript, you should give thought to the <a href="http://warpspire.com/posts/url-design/">design of your URLs</a>. Make them meaningful and organised. Make sure you can directly access them without JavaScript. Only then should you add your JavaScript to enhance the browsing experience.</p>
</section>
<div id="crp_related">
<h3>Related Posts:</h3>
<ul class="related">
<li><a href="http://html5doctor.com/server-sent-events/" rel="bookmark" class="crp_title">Server-Sent Events</a></li>
<li><a href="http://html5doctor.com/how-to-get-all-the-browsers-playing-ball/" rel="bookmark" class="crp_title">How to get all the browsers playing ball</a></li>
<li><a href="http://html5doctor.com/methods-of-communication/" rel="bookmark" class="crp_title">Methods of communication</a></li>
<li><a href="http://html5doctor.com/storing-data-the-simple-html5-way-and-a-few-tricks-you-might-not-have-known/" rel="bookmark" class="crp_title">Storing Data the Simple HTML5 Way (and a few tricks you might not have known)</a></li>
<li><a href="http://html5doctor.com/native-drag-and-drop/" rel="bookmark" class="crp_title">Native Drag and Drop</a></li>
</ul>
</div>
<p><a href="http://html5doctor.com/history-api/" rel="bookmark">Pushing and Popping with the History API</a> originally appeared on <a href="http://html5doctor.com">HTML5 Doctor</a> on November 15, 2011.</p>
]]></content:encoded>
			<wfw:commentRss>http://html5doctor.com/history-api/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>The return of the u element</title>
		<link>http://html5doctor.com/u-element/</link>
		<comments>http://html5doctor.com/u-element/#comments</comments>
		<pubDate>Tue, 25 Oct 2011 14:00:37 +0000</pubDate>
		<dc:creator>Oli Studholme</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[Elements]]></category>
		<category><![CDATA[Specification Changes]]></category>
		<category><![CDATA[HTML 5]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[u]]></category>

		<guid isPermaLink="false">http://html5doctor.com/?p=3862</guid>
		<description><![CDATA[<p>The <code>&#60;u&#62;</code> element was deprecated in HTML 4 and non-conforming in HTML5, but a couple of use cases have seen it return from the dead. Are the use cases enough to persuade you that it’s a phoenix not a zombie?</p>]]></description>
			<content:encoded><![CDATA[<p>Presentational elements like <a href="http://html5doctor.com/i-b-em-strong-element/" title="The i, b, em, &amp; strong elements | HTML5 Doctor"><code>&lt;i&gt;</code>, <code>&lt;b&gt;</code></a>, <a href="http://html5doctor.com/small-hr-element/" title="The small &amp; hr elements | HTML5 Doctor"><code>&lt;small&gt;</code> and <code>&lt;hr&gt;</code></a> have been redefined in HTML5 with semantic meanings, or, in a couple of cases, made non-conforming. The <code>&lt;u&gt;</code> element had been in the non-conforming camp, but a couple of semantic use cases led it back into the fold. While most of us will never need it (and some will jeer), on the odd occasion, it might be just the element you need.</p>

<p>Before HTML5, <code>&lt;u&gt;</code> was solely for applying a presentational style of <em>underlining</em> to text. <a href="http://www.w3.org/TR/html401/present/graphics.html#h-15.2" title="Alignment, font styles, and horizontal rules in HTML documents">HTML 4 discouraged “font-style” or presentational elements</a>, and even <a href="http://www.w3.org/TR/html401/appendix/changes.html#idx-deprecated" title="HTML 4 Changes">deprecated <code>&lt;u&gt;</code></a>, advising us to use CSS instead. Even before this, <code>&lt;u&gt;</code> was frowned upon as underlines are the browser default for links, and making normal text look like links gives users a bad case of clicky-clicky frustration. <code>&lt;u&gt;</code> was initially non-conforming in HTML5.</p>

<p>There are, however, a couple of non-link places where text <em>is</em> traditionally underlined to convey meaning, as the HTML5 specification’s definition mentions:</p>

<blockquote>
<p>The <code>u</code> element represents a span of text with an unarticulated, though explicitly rendered, non-textual annotation, such as labeling the text as being a proper name in Chinese text (a Chinese proper name mark), or labeling the text as being misspelt.</p>
<footer>— <cite><a href="http://www.whatwg.org/specs/web-apps/current-work/complete/text-level-semantics.html#the-u-element" title="4.6 Text-level semantics &#8212; Web Applications 1.0"><abbr title="">WHATWG</abbr> HTML5 specification</a></cite></footer>
</blockquote>

<p>Before we get to them, let’s quickly cover <em>an unarticulated, though explicitly rendered, non-textual annotation</em>. This means <q><code>&lt;u&gt;</code> is for when you are annotating something, but not explicitly saying what it is</q> (<cite><a href="http://krijnhoetmer.nl/irc-logs/whatwg/20110930#l-916" title="IRC logs: freenode / #whatwg / 20110930">WHATWG IRC</a></cite>, Ian Hickson) — the annotation’s meaning is implied by context.</p>

<section id="proper-name-mark">
<h2>Chinese proper name marks <a class="permalink" href="#proper-name-mark">#</a></h2>

<p>And what exactly are those you ask? I had to ask Wikipedia myself:</p>

<blockquote>
<p>In Chinese writing, a proper name mark (Simplified Chinese: <span lang="Hans">专名号</span>, <span lang="zh-Latn">zhuānmínghào</span>; Traditional Chinese: <span lang="Hant">專名號</span>) is an underline used to mark proper names, such as the names of people, places, dynasties, organizations. … This method of recognizing proper names in text is similar to the English use of a capital letter.</p>
<footer>— <cite><a href="http://en.wikipedia.org/wiki/Proper_name_mark" title="Proper name mark - Wikipedia, the free encyclopedia">Proper name mark</a></cite>, Wikipedia</footer>
</blockquote>

<p>Wikipedia gives the following example, which I’ve formatted using <code>&lt;u&gt;</code>:</p>

<figure id="pnm">
<style scoped>#pnm .pnm, #pnm .bnm {text-decoration: underline;}
#pnm .bnm {
  -moz-text-decoration-style: wavy;
  text-decoration-style: wavy;
}
#pnm p[lang="zh"] cite {font-style: normal;}</style>
<pre><code lang="zh">&lt;u class="pnm"&gt;屈原&lt;/u&gt;放逐，乃賦&lt;cite class="bnm"&gt;離騒&lt;/cite&gt;。&lt;u class="pnm"&gt;左丘&lt;/u&gt;失明，厥有&lt;cite class="bnm"&gt;國語&lt;/cite&gt;。（司馬遷 《&lt;cite&gt;報任安書&lt;/cite&gt;》）</code></pre>
<p lang="zh"><u class="pnm">屈原</u>放逐，乃賦<cite class="bnm">離騒</cite>。<u class="pnm">左丘</u>失明，厥有<cite class="bnm">國語</cite>。（司馬遷 《<cite>報任安書</cite>》）</p>
<!-- The source doesn’t use proper and book name marks for the citation because modern usage is only to use guillemets for the title — only the quoted text is classical -->
<p><mark lang="zh">Qu Yuan</mark> was exiled, and thus composed the <mark lang="zh"><cite>Li Sao</cite></mark>. <mark lang="zh">Zuo Qiu</mark> lost his sight, hence there is the <mark lang="zh"><cite>Guo Yu</cite></mark>. (<span lang="zh">Sima Qian</span>, “<cite>Letter to <span lang="zh">Ren'an</span></cite>”)</p>
<figcaption>Using <code>&lt;u&gt;</code> for Chinese proper name marks where appropriate</figcaption>
</figure>

<p>If you’re using Firefox 6+ you’ll also see the appropriate wavy underline for a Chinese book name mark on the quote’s source, courtesy of CSS3’s <code>text-decoration-style: wavy;</code>. I’ve used <code>&lt;cite&gt;</code> for book name marks as it’s more appropriate than <code>&lt;u&gt;</code>. You can find out more about <code>wavy</code> in <a href="http://dev.w3.org/csswg/css3-text/Overview.html#decoration" title="CSS Text Level 3">CSS Text Level 3</a>.</p>

<!-- /#proper-name-mark --></section>

<section id="spell-check">
<h2>Using <code>&lt;u&gt;</code> for spell-checking feedback <a class="permalink" href="#spell-check">#</a></h2>

<p>While you’re probably not marking up classical Chinese prose, a more familiar use case is for a spell-checker to indicate incorrect text. The default formatting in word processors is typically a red underline for spelling errors, and a green underline for grammatical errors:</p>

<figure id="spelling">
<style scoped>#spelling .spelling-error {
  text-decoration: none;
  border-bottom: 1px dashed red;
}
#spelling .grammatical-error {
  text-decoration: none;
  border-bottom: 1px dashed green;
}</style>
<pre><code>.spelling-error {
  text-decoration: none;
  border-bottom: 1px dashed red;
}
.grammatical-error {
  text-decoration: none;
  border-bottom: 1px dashed green;
}
&lt;p&gt;hello doctor i am having a huge body &lt;u class="spelling-error"&gt;oder&lt;/u&gt; &lt;u class="grammatical-error"&gt;it is smell really bad&lt;/u&gt;&lt;/p&gt;</code></pre>
<p>hello doctor i am having a huge body <u class="spelling-error">oder</u> <u class="grammatical-error">it is smell really bad</u></p>
<figcaption>Using <code>&lt;u&gt;</code> for annotating spell checker feedback</figcaption>
</figure>

<p>While we’ve turned off the default <code>text-decoration</code> style, <code>&lt;u&gt;</code> will back us up if CSS is disabled, and potentially provide more information for assistive technology. After all, if it’s semantic it should be in HTML, not CSS.</p>

<p>Some word processors use wavy underlines. This CSS would have the same effect in a supporting browser:</p>

<pre><code>.spelling-error {
  text-decoration-line: underline;
  text-decoration-style: wavy;
  text-decoration-color: red;
}
.grammatical-error {
  text-decoration-line: underline;
  text-decoration-style: wavy;
  text-decoration-color: green;
}</code></pre>

<p>Or, using <code>text-decoration</code> as a shorthand property, and adding a default declaration for non-supporting browsers:</p>

<pre><code>.spelling-error {
  text-decoration: underline; /* for backwards compatibility */
  text-decoration: underline wavy red;
}
.grammatical-error {
  text-decoration: underline; /* for backwards compatibility */
  text-decoration: underline wavy green;
}</code></pre>

<p>Again, you can read more about the upgraded <code>text-decoration</code> properties in <a href="http://dev.w3.org/csswg/css3-text/Overview.html#decoration" title="CSS Text Level 3">CSS Text Level 3</a>.</p>

<!-- /#spell-check --></section>

<section id="family-names">
<h2>Using <code>&lt;u&gt;</code> for indicating family names <a class="permalink" href="#family-names">#</a></h2>

<p>Another use for <code>&lt;u&gt;</code> is to annotate a family name when this might be confusing — Chinese, Japanese, Korean and Vietnamese (among others) all traditionally write names in a different order than the western-centric “given-name family-name”. While applying a blanket western ordering is fairly common (especially when publishing in English), it’s good form to use culturally appropriate ordering. If the audience might misunderstand, the family name can be underlined, capitalised, or otherwise annotated to make the name order explicit. For example, the <abbr title="Central Intelligence Agency">CIA</abbr>’s World Fact Book capitalises the family name:</p>

<blockquote>
<p>After World War II, the Communists under <mark>MAO Zedong</mark> established an autocratic socialist system …</p>
<footer>— <cite><a href="https://www.cia.gov/library/publications/the-world-factbook/geos/ch.html">The World Factbook</a></cite>, <abbr title="Central Intelligence Agency">CIA</abbr></footer>
</blockquote>

<p>This ties in nicely with <a href="http://html5doctor.com/microformats/#hcard" title="Extending HTML5 — Microformats | HTML5 Doctor">the hCard microformat</a>, as the “implied <code>n</code> optimisation” doesn’t work with these non-western ordered names, and we need a wrapper element to indicate each part of the name anyhow.</p>

<figure id="family-name1">
<style scoped>#family-name1 .family-name {text-decoration: underline;}</style>
<pre><code>&lt;style&gt;
  .family-name {text-decoration: underline;}
&lt;/style&gt;
&lt;p&gt;
  &lt;span class="vcard" lang="ja-latn"&gt;
    &lt;span class="fn n"&gt;
      &lt;u class="family-name"&gt;Son&lt;/u&gt; &lt;span class="given-name"&gt;Goku&lt;/span&gt;
    &lt;/span&gt;
  &lt;/span&gt;
   is the main protagonist in 
  &lt;span class="vcard" lang="ja-latn"&gt;
    &lt;span class="fn n"&gt;
      &lt;span class="given-name"&gt;Akira&lt;/span&gt; &lt;u class="family-name"&gt;Toriyama&lt;/u&gt;
    &lt;/span&gt;
  &lt;/span&gt;’s &lt;i lang="ja-latn"&gt;manga&lt;/i&gt; “Dragon Ball”.
&lt;/p&gt;</code></pre>
<p><span class="vcard" lang="ja-latn"><span class="fn n"><u class="family-name">Son</u> <span class="given-name">Goku</span></span></span> is the main protagonist in <span class="vcard" lang="ja-latn"><span class="fn n"><span class="given-name">Akira</span> <u class="family-name">Toriyama</u></span></span>’s <i lang="ja-latn">manga</i> “Dragon Ball”.</p>
<figcaption>Using <code>&lt;u&gt;</code> to indicate the family name in non-western names via underlining</figcaption>
</figure>

<p>Of course you can then change the style via CSS, for example</p>

<figure id="family-name2">
<style scoped>#family-name2 .family-name {
  text-decoration: none;
  text-transform: uppercase;
}</style>
<pre><code>.family-name {
  text-decoration: none;
  text-transform: uppercase;
}
</code></pre>
<p><span class="vcard" lang="ja-latn"><span class="fn n"><u class="family-name">Son</u> <span class="given-name">Goku</span></span></span> is the main protagonist in <span class="vcard" lang="ja-latn"><span class="fn n"><span class="given-name">Akira</span> <u class="family-name">Toriyama</u></span></span>’s <i lang="ja-latn">manga</i> “Dragon Ball”.</p>
<figcaption>Using <code>&lt;u&gt;</code> to indicate the family name in non-western names via capitalisation</figcaption>
</figure>

<p>The benefit of using <code>&lt;u&gt;</code> for this is the family name will be indicated even when CSS is disabled, ensuring the annotation isn’t lost. Assistive technology may also be able to inform the user of this in the future.</p>

<!-- /#family-names --></section>

<section id="do-we-need-u">
<h2>But do we need <code>&lt;u&gt;</code>? <a class="permalink" href="#do-we-need-u">#</a></h2>

<p>A lot of people bitten by the web standardista bug have somewhat of an allergic reaction to ex-presentational elements in HTML5, after influential articles like Tantek Çelik’s “<a href="http://tantek.com/log/2002/10.html#L20021022t1432" title="tantek/log/2002/10"><code>&lt;b&gt;</code>ed and <code>&lt;br&gt;</code>eakfast markup</a>”. Given <code>&lt;u&gt;</code>’s ignoble past, I expect the reaction to its return will also lead to some poo-pooing. As we already mentioned, however, <em>if it imparts meaning, it should be in HTML</em>. These use cases involve semantic meaning, and even without assistive technology support, <code>&lt;u&gt;</code> conveys some meaning to sighted users via the browser-default style <code>text-decoration: underline;</code>.</p>

<p>Regardless of whether an element is deprecated (HTML 4, XHTML 1)  or non-conforming (HTML5) or just plain uncool, browser makers still have to support it for backward compatibility with all those awesome web pages from the days when <code>&lt;blink&gt;</code> was hawt. Because of this, if there’s a semantic use case for an ex-presentational element, it’s definitely better to reform it rather than minting a new element with no backward compatibility. You might think <code>&lt;mark&gt;</code> sounds pretty similar, but the default browser styling would be completely wrong for proper name marks, and <a href="http://krijnhoetmer.nl/irc-logs/whatwg/20110930#l-890" title="IRC logs: freenode / #whatwg / 20110930">semantically less appropriate for spelling errors</a> too.</p>

<p>As Ian Hickson explains:</p>

<blockquote>
<p>The presentational markup that was <code>&lt;u&gt;</code>, <code>&lt;i&gt;</code>, <code>&lt;b&gt;</code>, <code>&lt;font&gt;</code>, <code>&lt;small&gt;</code>, etc, is gone. However, there are certain use cases that did not yet have elements yet were important enough to warrant us supporting them. By reusing existing elements, we are able to support them without having to wait for new elements to be implemented. By doing so in a way that closely matches how those elements were actually used in practice (at least to the same extent as other elements have been correctly used in practice) we can not only have older UAs support these new elements automatically, but we can do so in a way that does not introduce an undue volume of invalid pages.</p>
<footer>— <a href="http://lists.whatwg.org/pipermail/whatwg-whatwg.org/2011-July/032715.html" title="[whatwg] sic element">WHATWG email list</a>, Ian Hickson</footer>
</blockquote>

<!-- /#do-we-need-u --></section>

<section id="conclusion">
<h2>Conclusion</h2>

<p>Given the potential to confuse underlined text with links, using <code>text-decoration: underline;</code> on anything other than <code>&lt;a&gt;</code> is bad pretty much all the time. <strong>Generally <code>&lt;u&gt;</code> is not the element you’re looking for</strong>, even for Chinese book name marks (<code>&lt;cite&gt;</code> would be more appropriate). <em>However</em>, for at least these three use cases, it’s good to have a semantic option, something better than <code>&lt;span&gt;</code>.</p>

<p>So…in a hypothetical world where you did need to code for one of these situations, would you use <code>&lt;u&gt;</code> or something else like <code>&lt;span&gt;</code>? Let us know in the comments!</p>

<!-- /#conclusion --></section>
<div id="crp_related"><h3>Related Posts:</h3><ul class="related"><li><a href="http://html5doctor.com/ruby-rt-rp-element/" rel="bookmark" class="crp_title">The ruby element and her hawt friends, rt and rp</a></li><li><a href="http://html5doctor.com/blockquote-q-cite/" rel="bookmark" class="crp_title">Quoting and citing with <code>&lt;blockquote&gt;</code>, <code>&lt;q&gt;</code>, <code>&lt;cite&gt;</code>, and the cite attribute</a></li><li><a href="http://html5doctor.com/i-b-em-strong-element/" rel="bookmark" class="crp_title">The i, b, em, &amp; strong elements</a></li><li><a href="http://html5doctor.com/html-5-reset-stylesheet/" rel="bookmark" class="crp_title">HTML5 Reset Stylesheet</a></li><li><a href="http://html5doctor.com/the-address-element/" rel="bookmark" class="crp_title">The Address Element</a></li></ul></div><p><a href="http://html5doctor.com/u-element/" rel="bookmark">The return of the u element</a> originally appeared on <a href="http://html5doctor.com">HTML5 Doctor</a> on October 25, 2011.</p>
]]></content:encoded>
			<wfw:commentRss>http://html5doctor.com/u-element/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		</item>
		<item>
		<title>Dive into HTML5… on HTML5 Doctor</title>
		<link>http://html5doctor.com/dive-into-html5-doctor/</link>
		<comments>http://html5doctor.com/dive-into-html5-doctor/#comments</comments>
		<pubDate>Mon, 17 Oct 2011 12:50:57 +0000</pubDate>
		<dc:creator>Oli Studholme</dc:creator>
				<category><![CDATA[Misc]]></category>
		<category><![CDATA[books]]></category>
		<category><![CDATA[diveintohtml5]]></category>
		<category><![CDATA[HTML 5]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[Mark Pilgrim]]></category>

		<guid isPermaLink="false">http://html5doctor.com/?p=3886</guid>
		<description><![CDATA[<p>We were surprised and saddened when Mark Pilgrim decided to retire from the internet and take his writing, including “Dive into HTML5” with him. However the interwebs have your back. We’re adding a mirror of the book here to add to the growing list, and plan to help keep it updated. So long Mark, and thanks for all the &#60;>!</p>]]></description>
			<content:encoded><![CDATA[<p>Last week, we were surprised and saddened when Mark Pilgrim, long time educator, raconteur, and writer of note, decided to retire from the internet. Unfortunately, he also decided to <a href="http://meyerweb.com/eric/thoughts/2011/10/04/searching-for-mark-pilgrim/" title="“Embracing HTTP error code 410 means embracing the impermanence of all things” Meyerweb: Searching For Mark Pilgrim"><code>410: gone</code> all of his writing</a>, including <cite>Dive into HTML5</cite>.</p>

<p>Mark provided this book <em>for free</em> on the web (under a <a href="http://creativecommons.org/licenses/by/3.0/" title="Creative Commons — Attribution 3.0 Unported — CC BY 3.0">Creative Commons By 3.0 license</a>), in addition to a published, for-sale version entitled <a href="http://www.amazon.com/dp/0596806027"><cite>HTML5: Up and Running</cite> from O’Reilly</a>. This is a very unusual setup, but one we’ve collectively benefitted from. Many HTML5 Doctor articles feature links to this book, and the sudden loss of this valuable resource was a little shocking.</p>

<p>The interwebs soon mobilised, however, and now there are several copies of this book, including:</p>

<ul>
<li><a href="http://diveintohtml5.info">diveintohtml5.info</a> and <a href="http://diveinto.org">diveinto.org</a> (<a href="https://github.com/jonathantneal/diveintohtml5">GitHub</a>)</li>
<li><a href="http://mislav.uniqpath.com/diveintohtml5/" title="Dive Into HTML5">mislav.uniqpath.com</a> (<a href="https://github.com/mislav/diveintohtml5">GitHub</a>)</li>
<li><a href="http://diveintohtml5.ep.io">diveintohtml5.ep.io</a> (<a href="https://github.com/diveintomark/diveintohtml5">GitHub</a>)</li>
<li>A bunch of forks, site archives, and PDFs on GitHub and elsewhere, such as <a href="http://mislav.uniqpath.com/2011/10/dive-into-html5/" title="Dive into HTML5: In memory of Mark Pilgrim">Mislav Marohnić’s beautiful PDF eBook</a></li>
</ul>

<p>There are also several partial translations, including:</p>

<ul>
<li>Chinese: <a href="http://diveintohtml5.com">diveintohtml5.com</a> (<a href="https://github.com/diveintohtml5-zh-cn/diveintohtml5.zh-cn">GitHub</a>)</li>
<li>Japanese: <a href="https://github.com/myakura/dih5ja">GitHub</a> and <a href="http://hail2u.net/documents/diveintohtml5-semantics.html">hail2u.net</a></li>
<li>Czech: <a href="http://kniha.html5.cz/">kniha.html5.cz</a> (<a href="https://github.com/met/diveintohtml5">GitHub</a>)</li>
<li>French: <a href="http://www.jeremyselier.com/diveintohtml5/">jeremyselier.com</a></li>
</ul>

<p><em>(Please leave a comment if you know of any others!)</em></p>

<p>Jonathan Neal is coordinating diveintohtml5.info and diveinto.org, and has added the following to the book’s title page:</p>

<blockquote>
<p>Mark Pilgrim has stopped maintaining this project, and we want it to continue. We’re not just patching broken links and updating APIs. We plan to actively maintain it; refreshing, updating, and reflecting the relevant and current state of HTML5, just as it had been during Mark’s tenure.</p>
<footer>— <cite><a href="http://diveintohtml5.info/" title="Dive Into HTML5">diveintohtml5.info</a></cite>, <a href="https://twitter.com/jon_neal">Jonathan Neal</a></footer>
</blockquote>

<p>We doctors feel the same way and plan to help keep the book updated. To that end, we’ve set up a mirror at <a href="http://diveinto.html5doctor.com" title="Dive Into HTML5"><strong>diveinto.html5doctor.com</strong></a>, and we’ll be experimenting with using <a href="https://github.com/html5doctor/diveintohtml5">GitHub</a> to contribute.</p>

<p>We’d like to publicly thank Mark Pilgrim for both writing this wonderful reference on HTML5 (and all his other writing over the years), and for making <cite>Dive into HTML5</cite> available under a CC-By license that makes it possible for us to mirror it here. We’re interested to see where this brave new world of distributed community editing collectively takes us, and <a href="https://github.com/html5doctor/diveintohtml5">we invite you to pitch in</a>.</p>
<div id="crp_related"><h3>Related Posts:</h3><ul class="related"><li><a href="http://html5doctor.com/review-html5-designing-rich-internet-applications/" rel="bookmark" class="crp_title">Review: HTML5 Designing Rich Internet Applications</a></li><li><a href="http://html5doctor.com/html5-for-web-developers/" rel="bookmark" class="crp_title">HTML5 for Web Developers</a></li><li><a href="http://html5doctor.com/the-scoped-attribute/" rel="bookmark" class="crp_title">The scoped attribute</a></li><li><a href="http://html5doctor.com/server-sent-events/" rel="bookmark" class="crp_title">Server-Sent Events</a></li><li><a href="http://html5doctor.com/how-to-get-all-the-browsers-playing-ball/" rel="bookmark" class="crp_title">How to get all the browsers playing ball</a></li></ul></div><p><a href="http://html5doctor.com/dive-into-html5-doctor/" rel="bookmark">Dive into HTML5… on HTML5 Doctor</a> originally appeared on <a href="http://html5doctor.com">HTML5 Doctor</a> on October 17, 2011.</p>
]]></content:encoded>
			<wfw:commentRss>http://html5doctor.com/dive-into-html5-doctor/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Review: HTML5 Now (DVD)</title>
		<link>http://html5doctor.com/review-html5-now-dvd/</link>
		<comments>http://html5doctor.com/review-html5-now-dvd/#comments</comments>
		<pubDate>Tue, 04 Oct 2011 13:30:30 +0000</pubDate>
		<dc:creator>Richard Clark</dc:creator>
				<category><![CDATA[Reviews]]></category>
		<category><![CDATA[dvd]]></category>
		<category><![CDATA[HTML 5]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[html5now]]></category>
		<category><![CDATA[tantek]]></category>

		<guid isPermaLink="false">http://html5doctor.com/?p=3624</guid>
		<description><![CDATA[<p>We all learn in different ways. Some of us are readers or writers, some are kinesthetic learners, some prefer video or audio. If you fall into either of the latter two categories, Tantek Çelik’s DVD HTML5 Now might just be for you.</p>]]></description>
			<content:encoded><![CDATA[<p>We all learn in different ways. Some of us are readers or writers, some are kinesthetic learners, some prefer video or audio. If you fall into either of the latter two categories, <a href="http://twitter.com/t">Tantek Çelik’s</a> DVD <cite>HTML5 Now</cite> (Figure 1) might just be for you.</p>

<figure>
  <img src="http://html5doctor.com/wp-content/uploads/2011/09/html5-now.jpg" alt="HTML5 DVD">
  <figcaption>Figure 1: <cite>HTML5 Now</cite> DVD by Tantek Çelik</figcaption>
</figure>

<section>
  <h2>Overview</h2>
  <p>Personally, I’ve never been keen on video-based learning like this. As such, I wasn’t sure what I’d make of <cite>HTML5 Now</cite>. It turns out I was pleasantly surprised by the format, the content, and the presentation.</p>
  
  <p>Tantek has an natural, engaging presentation style, and his knowledge of the subject area ranks up there with the best of them. He begins with an interesting historical look at HTML and in turn how HTML5 came to be. This section is full of things you might not know about HTML, let alone HTML5.</p>
  
  <p>A few other thoughts:</p>
  
  <ul>
    <li>Tantek constantly urges you to get involved and share your experiences.</li>
    <li>The early parts of the DVD contain in-depth background information on elements and attributes.</li>
    <li>Tantek presents a clear, concise introduction to <code>&lt;ruby&gt;</code> and friends, even explaining how it’s worked in IE for 10+ years!</li>
    <li>He introduces his bulletproof HTML5 syntax (using <code>&lt;div&gt;</code>s with class names inside new elements).</li>
    <li>The accompanying booklet effectively takes notes for you so you don’t have to. Just sit back and enjoy!</li>
    <li>The DVD also contains the slides shown throughout the presentation and a PDF of the booklet.</li>
    <li>A few tongue-tied moments help keep it real, not staged or forced. It shows Tantek really cares about the subject.</li>
    <li>You’ll get some good tips on when to use the new elements. Additionally, some elements are more stable since the DVD was released.</li>
    <li>Each section is concluded by a brief summary recapping what you’ve learnt.</li>
  </ul>
</section>

<section>
  <h2>Words of warning</h2>
  <p>As is the case with any book or DVD based on the constantly evolving HTML5 specification, parts of the DVD are now out of date. (It was originally released in July 2010.) Look out for these gotchas:</p>
  
  <ul>
    <li>Certain sections don’t mention browser support.</li>
    <li><code>&lt;u&gt;</code> is now a part of the HTML5 specification.</li>
    <li>The WebM video codec didn’t exist at the time of production.</li>
    <li>There is no mention of form attributes and support for the new input types.</li>
    <li><code>&lt;canvas&gt;</code> is incorrectly described as a vector format (it’s bitmap).</li>
    <li>It’s a shame that Tantek only scratches the surface of <code>&lt;video&gt;</code>, <code>&lt;audio&gt;</code>, <code>&lt;canvas&gt;</code>, and SVG. They each deserve their own DVD!</li>
  </ul>
</section>

<section>
  <h2>Summary</h2>
  <p>I’m still not convinced that DVD is the best format for this type of content. As with print, it goes out of date very quickly. Alternatively, you could simply publish the video(s) on a website and make them available on a subscription basis. That way, outdated information could be updated more regularly. That’s a discussion for another day, though, and I’m sure Tantek would be keen to see it happen.</p>
  
  <p>In my opinion, the DVD is better suited to someone who has some prior knowledge of HTML and HTML5. It’s certainly not for beginners, but it does come recommended. You’ll definitely learn something. I’ll leave you with a video of Tantek (Figure 2) discussing the state of HTML5 at the Voices that Matter Conference just before the DVD was released:</p>

  <figure>
    <iframe width="500" height="375" src="http://www.youtube.com/embed/gUl9GdNk92o" frameborder="0" allowfullscreen></iframe>
    <figcaption>Figure 2: Tantek Çelik at the Voices That Matter: Web Design Conference 2010.</figcaption>
  </figure>
</section><div id="crp_related"><h3>Related Posts:</h3><ul class="related"><li><a href="http://html5doctor.com/review-html5-designing-rich-internet-applications/" rel="bookmark" class="crp_title">Review: HTML5 Designing Rich Internet Applications</a></li><li><a href="http://html5doctor.com/video-the-track-element-and-webm-codec/" rel="bookmark" class="crp_title">Video: the track element and webM codec</a></li><li><a href="http://html5doctor.com/video-subtitling-and-webvtt/" rel="bookmark" class="crp_title">Video Subtitling and WebVTT</a></li><li><a href="http://html5doctor.com/the-video-element/" rel="bookmark" class="crp_title">The video element</a></li><li><a href="http://html5doctor.com/an-introduction-to-the-canvas-2d-api/" rel="bookmark" class="crp_title">An introduction to the Canvas 2D API</a></li></ul></div><p><a href="http://html5doctor.com/review-html5-now-dvd/" rel="bookmark">Review: HTML5 Now (DVD)</a> originally appeared on <a href="http://html5doctor.com">HTML5 Doctor</a> on October 4, 2011.</p>
]]></content:encoded>
			<wfw:commentRss>http://html5doctor.com/review-html5-now-dvd/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>HTML5: briefing notes for journalists and analysts</title>
		<link>http://html5doctor.com/html5-briefing-notes-journalists-analysts/</link>
		<comments>http://html5doctor.com/html5-briefing-notes-journalists-analysts/#comments</comments>
		<pubDate>Tue, 20 Sep 2011 06:54:13 +0000</pubDate>
		<dc:creator>Bruce Lawson</dc:creator>
				<category><![CDATA[Marketing]]></category>
		<category><![CDATA[Misc]]></category>
		<category><![CDATA[HTML 5]]></category>
		<category><![CDATA[html5]]></category>

		<guid isPermaLink="false">http://html5doctor.com/?p=3547</guid>
		<description><![CDATA[<p>Your friendly neighbourhood doctors are often contacted by  journalists and analysts who have questions about HTML5, usually from a consumer of business perspective. This is great, as we spend many more hours every week mutely shaking our heads while reading the ill-informed columns from journalists or analysts who haven't contacted us.</p>
]]></description>
			<content:encoded><![CDATA[<p>Your friendly neighbourhood doctors are often contacted by  journalists and analysts who have questions about HTML5, usually from a consumer or business perspective. This is great, as we spend many more hours every week mutely shaking our heads while reading the <a href="http://www.brucelawson.co.uk/2011/html5-notes-for-analysts-and-journalists/">ill-informed columns</a> from journalists or analysts who haven&#8217;t contacted us.</p>
<p>Here are the most common questions we&#8217;re asked, with non-technical answers. Journos &#8211; you&#8217;re welcome to use these answers (a citation would be nice but isn&#8217;t required).</p>
<p>We&#8217;ll add new questions and answers as they are asked.</p>
<h2>What is HTML5?</h2>
<p>Depends what you mean. There are 3 different uses of the phrase &quot;HTML5&quot;:</p>
<h3>The HTML5 specification</h3>
<p>The most accurate meaning of HTML5 is the specification that is developed by two groups, the <a href="http://en.wikipedia.org/wiki/World_Wide_Web_Consortium">W3C</a> and <a href="http://en.wikipedia.org/wiki/Whatwg">WHATWG</a>, together. There are <a href="http://html5doctor.com/html5-for-web-developers/">different versions</a> of the core HTML5 specification.
<p>It is a much-needed evolution of the language that web pages are written in, and is designed for writing Web <strong>applications</strong> (dynamic interactive web pages that do something). Its predecessor, HTML4, dating from the late 1990s, was written for  Web <strong>Pages</strong> (static, hyperlinked documents of text, images, forms).
<p>Key facts:
<ul>
  <li>It&#8217;s designed to make web pages interoperable across browsers. These days, people use multiple browsers (For example, IE at work, Safari/ Opera on their phone, Opera/ Firefox at home) and it&#8217;s stupid and annoying if a website doesn&#8217;t work everywhere.</li>
  <li>All the browser manufacturers &#8211; Opera, Mozilla (Firefox), Apple (Safari), Microsoft (Internet Explorer), Google (Chrome) &#8211; are working together, along with loads of other individuals and organisations: Netflix, Adobe, IBM, HP, BBC etc.</li>
  <li>It&#8217;s designed to extend the capabilities of the current web, without breaking existing web pages </li>
  <li>It competes with plugins like Microsoft Silverlight and Adobe Flash (which themselves were developed to plug the holes in fossilized HTML4 standard)</li>
</ul>

<h3>HTML5 and close friends</h3>
<p>In addition to the core HTML5 specification, the WHATWG developed other specifications such as


<a href="http://en.wikipedia.org/wiki/Web_Workers">Web Workers</a>, <a href="http://dev.w3.org/html5/websockets/">Web Sockets</a>, <a href="http://www.w3.org/TR/webdatabase/">Web Database</a>. These add more features useful in applications, games and the like.
<p>(Many of these have been part of the core spec at some point, but moved out for procedural/ organisational reasons. They are all grouped together in a specification called <a href="http://www.whatwg.org/specs/web-apps/current-work/complete/">Web Applications 1.0)</a>.
<h3>New, Exciting Web Technologies</h3>
<p>When most non-developers (and many less-informed developers) say &#8220;HTML5&#8243; they are referring to a whole slew of technologies: Core HTML5, its friends and others entirely unrelated technologies, such as  <a href="/finding-your-position-with-geolocation/">Geolocation</a> (the ability for your browser to &#8220;know&#8221; its location), Device Orientation, Touch Events, CSS3 animations (that can replace very simple Flash animations), SVG (a way of describing graphics that look crisp and unpixellated at any screensize) and, the new kid on the block, <a href="http://en.wikipedia.org/wiki/WebGL">WebGL</a>, a port of a popular 3D graphics library to the Web that allows 3D graphics and games in the browser.</p>
<P>Many of these are developed by the W3C; WebGL is developed by <a href="http://en.wikipedia.org/wiki/Khronos_Group">Khronos Group</a>.</p>
<p>It&#8217;s also important to note that many so-called &quot;HTML5&quot; demos are nothing to do with HTML5 at all; many Google Doodles, for example, use <a href="http://en.wikipedia.org/wiki/Dhtml">DHTML</a> &#8211; an HTML 4 technology from the turn of the millennium.
<h2>Why has HTML5 been invented?</h2>
<p>HTML 4 was creaking at the seams for the new breed of applications. Some things were impossible and needed plugins like Adobe Flash or Microsoft Silverlight; other things required elaborate hacks on undocumented features, which wasn&#8217;t a robust foundation for websites that make money for their owners.</p>
<h2>How many HTML5-compliant browsers are there?</h2>
<p>It depends on your definition. Because HTML5 extends HTML4, by definition all browsers have some HTML5 features.</p>
<p>If, on the other hand, you want to know which browsers include all Core HTML5 features, none of them do. They are all implementing pieces of the specification (which is 700+ pages long) but none implement all.</p>
<p>Disregarding all the hype, the modern versions of the browsers are all around the same level of implementation (although different browsers implement different features at different times, depending on the needs of their customers).</p>
<h2>Who&#8217;s driving HTML5?</h2>
<p>It began in Opera, in 2004, edited by Ian Hickson. Gradually all the other browser manufacturers joined. Hickson left Opera and joined Google, where he continues to edit the spec. </p>
<p>It&#8217;s fairest to say that browser manufacturers collaboratively drive the spec, with the W3C and many other organisations and individuals. Ultimately, it&#8217;s driven by the needs of  Web developers.</p>
<h2>Who&#8217;s using HTML5?</h2>
<p>Lots of people &#8211; not just tech companies: <a href="http://www.bostonglobe.com/">Boston Globe Newspaper</a>; <a href="http://www.nationwide.co.uk/default.htm">Nationwide Building Society</a>, <a href="http://www.yell.com/">Yell.com</a> and hundreds more. <a href="http://html5gallery.com/">HTML5gallery.com</a> showcases many HTML5 sites.</p>
<h2 id=ready>When will HTML5 be ready?</h2>
<p>Perhaps 2012. Perhaps 2022. It doesn&#8217;t matter; what matters is that a lot of it is implemented in browsers now, so it can be used now.</p>
<p>Saying that we can&#8217;t use HTML5 because it isn&#8217;t finished is like saying we can&#8217;t speak English because it isn&#8217;t finished.</p>
<h2>Is HTML5 incompatible with Internet Explorer?</h2>
<p>Nope. IE9 has good support. Support for some APIs can be patched into older browsers with a technique called <b>polyfilling</b> with JavaScript, or with plugins like Flash and Silverlight. Support for <code>&lt;canvas&gt;</code> can be faked in IE&lt;9. It&#8217;s generally the slow JavaScript engines in older browsers that cause problems. Video content can use a Flash fallback in older versions of all browsers.</p>
<p>It&#8217;s worth noting that many of the features in HTML5 (like <code>contenteditable</code>, 
the Drag and Drop API) were invented by  Microsoft and were included in IE5.</p>
<h2>Is HTML5 just about mobile?</h2>
<p>Absolutely not. Behind HTML5 are some <a href="http://www.w3.org/TR/html-design-principles/">Design Principles</a>, one of which states that it&#8217;s about <a href="http://www.w3.org/TR/html-design-principles/#universal-access">universal access</a>:</p>
<blockquote>
  <p>Features should be designed for universal access&hellip;Features should, when possible, work across different platforms, devices, and media.</p>
</blockquote>
<p>That said, there are several features that are useful on Mobile. If you&#8217;re looking at &quot;real&quot; HTML5, then the ability to continue to interact with a website even when offline via <a href="/go-offline-with-application-cache/">Application Cache (&#8220;Appcache&#8221;)</a> is a useful one. 
<p>The fact that you can use HTML5 &lt;canvas&gt; for animations on devices that, by choice or necessity, can&#8217;t use Adobe Flash can be advantageous.
<p>In the broader &quot;New Exciting Web Techologies&quot; definition of HTML5, Geolocation is a huge feature.
<h2>Will HTML5  kill Adobe Flash?</h2>
<p>No &#8211; or we hope not. For years Flash was the only way to add video to a page; now there is HTML5. This competition means both are getting better, which is great for developers. </p>
<p>Apple decided not to allow Flash on their iOS devices, which is what gave HTML5 video a great boost. It&#8217;s important to note that HTML5 multimedia on iOS is hardly a perfect platform:</p><ul>
<li><a href="http://blog.millermedeiros.com/2011/03/html5-video-issues-on-the-ipad-and-how-to-solve-them/">HTML5 video issues on the iPad and how to solve them</a></li>
<li><a href="http://blog.millermedeiros.com/2011/04/unsolved-html5-video-issues-on-ios/">Unsolved HTML5 video issues on iOS</a></li>
<li><a href="http://remysharp.com/2010/12/23/audio-sprites/">Audio Sprites (and fixes for iOS)</a></li>
</ul>
<p>For video that uses adaptive bit-rate streaming,  or Digital Rights Management (DRM), Flash remains a useful cross-browser tool.</p>

<p>It&#8217;s also necessary to realise that Flash does more than simply video. Some its basic functions like simple gaming have been usurped by HTML5 &lt;canvas&gt;, and the kind of trivial animations that it used to be used for (things spinning on hover, for example) are moved into <a href="http://en.wikipedia.org/wiki/Cascading_Style_Sheets">CSS 3</a>. However, for ease of authoring sophisticated animated content like  games and cartoons, it&#8217;s much easier for authors to write in Flash as Adobe&#8217;s authoring environment has many tools (tweening, timelines) that make it easy for visual developers. This will change as companies develop pleasant authoring environments for &lt;canvas&gt;, but it isn&#8217;t there yet.</p>
<p>(Adobe recently released a preview of a timeline-driven authoring environment for non-Flash animations called <a href="http://labs.adobe.com/technologies/edge/">Adobe Edge</a>. Ignore its claims to be &quot;HTML5&quot;; in its current early incarnation, it&#8217;s simply flying HTML 4&lt;div&gt;s around with JavaScript.)</p>
<h2>Will HTML5  kill mobile Apps?</h2>
<p>HTML5 (in the broadest sense of &quot;New Exciting Web Technologies&quot;) significantly enhance the capabilities of the Web. Two years ago, to access the Global Positioning System on the phone, you had to write a native app in C++ or Java or.NET or Objective C depending on platform. If you wanted to target all platforms, you write the same app multiple times. Now, you can access Geolocation data from JavaScript on every platform (and on laptops too!), by the user visiting a URL rather than downloading an app.</p>
<p>Open web technologies are providing access to the <a href="http://my.opera.com/core/blog/2011/03/23/webcam-orientation-preview">device&#8217;s camera and orientation</a>, the system <a href="https://mozillalabs.com/blog/2010/03/contacts-in-the-browser/">contact book</a>, peer-to-peer <a href="http://www.webrtc.org/">in-browser video conferencing</a>, the devices&#8217; file system, and many more. JavaScript engines are becoming almost as fast as native code, so the technical niche for native applications on high-end smartphones still exists, but is becoming smaller. On less sophisticated devices that can&#8217;t run fast JavaScript or a full web browser, native apps are still an important product.</p>
<p>There are non-technical reasons for apps, too. Operators like them very much: they can control distribution and therefore extract money from both purchasers and vendors. Whereas many people dislike the idea of a monolithic appstore and app approval process, some consumers value it. Appstores offer curation &#8211; consumers feel that the apps are vetted and therefore won&#8217;t wreck their phones, steal their identities or (shudder) expose them to Internet smut.</p>
<p>Apps built for one specific device can be highly integrated with the User Interface and User Experience conventions of that device. Some people see this as a compelling advantage. However, uptake of the Web doesn&#8217;t seem to have suffered because authors make one single website rather than  different websites for Linux, Mac and Windows. </p>
<h2>Any further questions?</h2>
<p>If you have any further questions, you can <a href="/ask-the-doctor/">ask the doctor</a>, or <a href="http://www.brucelawson.co.uk/contact/"> analysts/ accredited journalists can ask your author for a briefing</a>.</p>
<div id="crp_related"><h3>Related Posts:</h3><ul class="related"><li><a href="http://html5doctor.com/video-the-track-element-and-webm-codec/" rel="bookmark" class="crp_title">Video: the track element and webM codec</a></li><li><a href="http://html5doctor.com/native-audio-in-the-browser/" rel="bookmark" class="crp_title">Native Audio in the browser</a></li><li><a href="http://html5doctor.com/why-designers-should-care-about-html5/" rel="bookmark" class="crp_title">Why designers should care about HTML5</a></li><li><a href="http://html5doctor.com/the-video-element/" rel="bookmark" class="crp_title">The video element</a></li><li><a href="http://html5doctor.com/your-questions-12/" rel="bookmark" class="crp_title">Your Questions Answered #12</a></li></ul></div><p><a href="http://html5doctor.com/html5-briefing-notes-journalists-analysts/" rel="bookmark">HTML5: briefing notes for journalists and analysts</a> originally appeared on <a href="http://html5doctor.com">HTML5 Doctor</a> on September 20, 2011.</p>
]]></content:encoded>
			<wfw:commentRss>http://html5doctor.com/html5-briefing-notes-journalists-analysts/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>The scoped attribute</title>
		<link>http://html5doctor.com/the-scoped-attribute/</link>
		<comments>http://html5doctor.com/the-scoped-attribute/#comments</comments>
		<pubDate>Tue, 13 Sep 2011 13:30:57 +0000</pubDate>
		<dc:creator>Jack Osborne</dc:creator>
				<category><![CDATA[Attributes]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[HTML 5]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[semantics]]></category>
		<category><![CDATA[style]]></category>

		<guid isPermaLink="false">http://html5doctor.com/?p=3634</guid>
		<description><![CDATA[<p>The scoped attribute for the style element allows you to include styles mid-document that targets a specific element and its children. Depending upon how you look at this, it’ll either be a godsend or a curse. Once you’ve reached the end of this article, I hope you can form your own opinion.</p>]]></description>
			<content:encoded><![CDATA[<p>The <code>scoped</code> attribute for the <code>&lt;style&gt;</code> element allows you to include styles mid-document that targets a specific element and its children. Depending upon how you look at this, it’ll either be a godsend or a curse. Once you’ve reached the end of this article, I hope you can form your own opinion.</p>

<p>Let’s take a quick look at the spec:</p>

<blockquote>
<p>The <code>scoped</code> attribute is a boolean attribute. If set, it indicates that the styles are intended just for the subtree rooted at the style element’s parent element, as opposed to the whole Document.</p>
<footer>— <cite><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/semantics.html#attr-style-scoped" title="Scoped attribute — HTML5">WHATWG</a></cite></footer>
</blockquote>

<section id="bad">
<h2>Isn’t this bad practice?</h2>
<p>For years, we’ve been told (and have actively told others) to separate content and presentation layers. So why would we introduce something that seems to go against everything we’ve been preaching?</p>

<p>The separation of these layers is still vitally important, but let’s look at a few use cases to shed some light on why this attribute has been introduced. Scoped style provides a W3C-approved way to:</p> 

<ul>
  <li>Add one-off CSS styles.</li>
  <li>Add user-defined styles to wiki or CMS content.</li>
  <li>Add theme-defined styles via CMS plugins.</li>
  <li>Keep syndicated content together (e.g., keeping example code together with the example).</li>
</ul>
</section>

<section id="how-does">
<h2>How does it work?</h2>
<p>In this section, I’ll show you how this new attribute will work when it gets rolled out to browsers.</p>

<section id="starting">
<h3>Our starting point</h3>

<p>We’ll be using the following code sample as a starting point:</p>

<pre><code>&#60;article&#62;
  &#60;h1&#62;Style Scoped&#60;/h1&#62;
  &#60;p&#62;The scoped attribute for the style element will eventually allow for you to include style elements mid-document. To do this, you must mark up your style element with the scoped attribute.&#60;/p&#62;
  &#60;section&#62;
    &#60;h2&#62;How does it work?&#60;/h2&#62;
    &#60;p&#62;Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.&#60;/p&#62;
  &#60;/section&#62;
&#60;/article&#62;</code></pre>

<p>This is a basic example, with two headings and two paragraphs set within the article element.</p>
</section>

<section id="addingscope">
<h3>Adding the <code>scoped</code> attribute</h3>

<p>In the next example, we’ll change the foreground color of the second paragraph to red (from whatever was defined in the master CSS file):</p>

<pre><code>&#60;article&#62;
  &#60;h1&#62;Style Scoped&#60;/h1&#62;
  &#60;p&#62;The scoped attribute for the style element will eventually allow for you to include style elements mid-document. To do this, you must mark up your style element with the scoped attribute.&#60;/p&#62;
  &#60;section&#62;
    &#60;style <mark>scoped</mark>&#62;
      p { color: red; }
    &#60;/style&#62;
    &#60;h2&#62;How does it work?&#60;/h2&#62;
    &#60;p&#62;Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.&#60;/p&#62;
  &#60;/section&#62;
&#60;/article&#62;</code></pre>

<aside class="sidenote"><p>It’s worth noting that the <code>scoped</code> attribute can’t be the first attribute of the body element. I also received a validation error using <code>&#60;body style="..."&#62;</code>.</p></aside>

<p id="example">This screenshot shows how things might render in the browser:</p>

<figure>
<img src="http://html5doctor.com/wp-content/uploads/2011/09/scoped1.gif" alt="" title="scoped" width="526" height="297" class="alignnone size-full wp-image-3735" />
<figcaption>How the <code>scoped</code> attribute will render</figcaption>
</figure>
</section>
</section>

<section id="link">
<h2>Can I apply <code>scoped</code> to &#60;link&#62;?</h2>
<p>While I was writing this article, Dr. Rich asked whether it was possible to add this attribute to <code>&lt;link&gt;</code> elements. Turns out you can’t, but I stumbled across this tidbit in the WHATWG mailing list:</p>

<blockquote>
  <p>You can use &#60;style scoped&#62;@import url(whatever);&#60;/style&#62;</p>
  <p>And this even enables you to add some specific styles ([be they embedded] or from another external sheet) on a per-use basis if the need arises. For example, a long dissertation relying on many quotes may benefit from adding stronger visual highlights on the &#60;em&#62; elements within the last quote to reinforce the final conclusion.</p>
  <footer>— <cite><a href="http://lists.whatwg.org/htdig.cgi/whatwg-whatwg.org/2011-March/031049.html"> Eduard Pascuals WHATWG mailing list response #031049</a></cite></footer>
</blockquote>
</section>

<section id="compatibility">
<h2>Backwards compatibility</h2>	
<p>Unfortunately, scoped style isn’t all puppy dogs and kittens.</p>

<p>Since this newly introduced attribute isn’t understood by current browsers, CSS rules in <code>&#60;style scoped&#62;</code> are just added to the page’s CSS. Therefore, if you were to include a <code>scoped</code> style block mid-page, its declarations would be applied to every matching element in the document, regardless of whether the element were inside or outside of the scope’s range.</p>

<p>For the sake of backwards compatibility, Louis Lazaris has suggested <a href="http://www.impressivewebs.com/scoped-styles-html5/">a brand new element called <code>&#60;scopedstyle&#62;</code></a>. This new element would only be recognised by supporting browsers and ignored by everything else. This way, scoped styles wouldn’t be added to the whole document. Instead, the browser would just throw away the unrecognised <code>&lt;scopedstyle&gt;</code> element and move on.</p>
</section>

<section id="support">
<h2>Browser support</h2>

<table class="wide">
<caption>Browser support for <code>&lt;style scoped&gt;</code> <i>(as of <time datetime="2011-09-06">6th September, 2011</time>)</i></caption>
<thead>
<tr>
<th scope="col">Browser</th>
<th scope="col">Support</th>
</tr>
</thead>
<tbody>
<tr>
  <th scope="row">Chrome 13</th>
  <td>No</td>
</tr>
<tr>
  <th scope="row">Safari 5</th>
  <td>No</td>
</tr>
<tr>
  <th scope="row">Firefox 6</th>
  <td>No</td>
</tr>
<tr>
  <th scope="row">Opera 11.51</th>
  <td>No</td>
</tr>
<tr>
  <th scope="row">Internet Explorer 9</th>
  <td>No</td>
</tr>
</tbody>
</table>

<p>Currently, the <code>scoped</code> attribute isn’t working in any of the browser alpha versions (Opera.Next, Mozilla Aurora, or WebKit nightly builds). There’s work in progress by <a href="https://bugs.webkit.org/show_bug.cgi?id=49142">Roland Steiner for support in WebKit</a>.</p>
</section>

<section id="using-today">
<h2>Using <code>&#60;style scoped&#62;</code> today</h2>
<p>So you’ve read this article and decided that you <em>need</em> scoped style in your life. What now? Well, just like every other new HTML5 thing, we have a polyfill for it. <a href="http://twitter.com/#!/thingsinjars">Simon Madine</a> has created a <a href="https://github.com/thingsinjars/jQuery-Scoped-CSS-plugin">jQuery scoped CSS plugin on GitHub</a>.</p>

<aside class="sidenote"><p>Please note that Oli used a wrapper <code>&lt;div&gt;</code> because of <a href="http://www.w3.org/Bugs/Public/show_bug.cgi?id=13102">validation problems explained in this bug</a>.</p></aside>

<p>You could also assign a CSS prefix to target the section of your document you want to style. You’d still be able to stick your styles inline, but you’ve also provided a fallback for the older browsers. In fact, Dr. Oli has done just that on his <a href="http://html5doctor.com/blockquote-q-cite/">latest article</a>. (View source and search for <code>&#60;div class="faint"&#62;</code>.)</p>
</section>

<section id="opinions">
<h2>Opinions</h2>

<p>There’s no denying that we’re breaking backwards compatibility by introducing <code>&lt;style scoped&gt;</code>. To me, this just doesn’t make any sense. I feel this needs to be addressed by either creating a new element like <code>&lt;scopedstyle&gt;</code> or using some protective mechanism like the <code>&#60;!--</code> and <code>--&#62;</code> delimiters that have been used within <code>&lt;style&gt;</code> and <code>&lt;script&gt;</code> elements.</p>

<p>Let’s not end this article with negative sentiment, though. As with anything, it’s what you make of it. Scoped style is pretty plain vanilla, but if people abuse it, it’ll end up with a bad rap. <a href="http://html5doctor.com/author/olib/">Dr. Oli</a> has spoken at length about his love for this attribute as it allows him to have live code examples with the CSS in <code>&#60;pre&#62;</code> and also in a <code>&#60;style scoped&#62;</code> within a <code>&#60;figure&#62;</code>.</p>

<p>So now it’s time for you to express your views. What do you think about the new <code>scoped</code> attribute? Do you think it has a future? Should it be fast-tracked into the spec? Or do you think it’s a waste of time that could ultimately end up mixing our content and presentation layers together again? Let us know in the comments!</p>
</section><div id="crp_related"><h3>Related Posts:</h3><ul class="related"><li><a href="http://html5doctor.com/the-contenteditable-attribute/" rel="bookmark" class="crp_title">The contenteditable attribute</a></li><li><a href="http://html5doctor.com/u-element/" rel="bookmark" class="crp_title">The return of the u element</a></li><li><a href="http://html5doctor.com/the-details-and-summary-elements/" rel="bookmark" class="crp_title">The details and summary elements</a></li><li><a href="http://html5doctor.com/blockquote-q-cite/" rel="bookmark" class="crp_title">Quoting and citing with <code>&lt;blockquote&gt;</code>, <code>&lt;q&gt;</code>, <code>&lt;cite&gt;</code>, and the cite attribute</a></li><li><a href="http://html5doctor.com/the-output-element/" rel="bookmark" class="crp_title">The output element</a></li></ul></div><p><a href="http://html5doctor.com/the-scoped-attribute/" rel="bookmark">The scoped attribute</a> originally appeared on <a href="http://html5doctor.com">HTML5 Doctor</a> on September 13, 2011.</p>
]]></content:encoded>
			<wfw:commentRss>http://html5doctor.com/the-scoped-attribute/feed/</wfw:commentRss>
		<slash:comments>66</slash:comments>
		</item>
	</channel>
</rss>

