<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[HTML5 Hacks]]></title>
  <link href="http://html5hacks.com/atom.xml" rel="self"/>
  <link href="http://html5hacks.com/"/>
  <updated>2013-06-17T21:51:06-05:00</updated>
  <id>http://html5hacks.com/</id>
  <author>
    <name><![CDATA[Jesse Cravens and Jeff Burtoft]]></name>
    <email><![CDATA[jesse.cravens@gmail.com]]></email>
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[Add Narration to your Slide Deck with HTML5 Audio]]></title>
    <link href="http://html5hacks.com/blog/2013/06/17/add-narration-to-your-slide-deck-with-html5-audio/"/>
    <updated>2013-06-17T10:11:00-05:00</updated>
    <id>http://html5hacks.com/blog/2013/06/17/add-narration-to-your-slide-deck-with-html5-audio</id>
    <content type="html"><![CDATA[<p><strong>Most presenter will share their slide deck on the web after their presentation. But many times the slides are only a shell of the real talk. Fortunately, with HTML5 audio, we can add our voice back to our slides and recreate the real presentation.</strong></p>

<h2>Sample Example</h2>

<p>To show what we&rsquo;re trying to accomplish, I&rsquo;ve created <a href="http://kevinlamping.com/deck.narrator.js/sample/sample.html">a very basic slide deck with audio narration</a> which briefly describes the issue at hand.</p>

<h2>Audio on the Web</h2>

<p>Back when the web was just taking off, it was common (bad) practice to include audio on your page. I&rsquo;m not talking about a Flash-based music player, but rather the more primitive audio solution: <code>&lt;bgsound&gt;</code>. Those who were programming back when HTML 3.2 came out will be familiar with this oft-forgotten tag.</p>

<p>Luckily for us, <code>&lt;bgsound&gt;</code> isn&rsquo;t the end of the story. According to <a href="http://www.w3.org/wiki/HTML/Elements/bgsound">the latest W3C spec</a>, <code>&lt;bgsound&gt;</code> has a much friendlier HTML5 alternative that you&rsquo;ve likely heard of: the <code>&lt;audio&gt;</code> tag.</p>

<p>So what benefits does <code>&lt;audio&gt;</code> bring us? Well, <code>&lt;bgsound&gt;</code> was an IE only property. <code>&lt;audio&gt;</code> on the other hand has wide support, with only IE 7 &amp; 8 lacking functionality. <code>&lt;audio&gt;</code> also allows API access so that we can control playback, seek through the audio, and even manipulate the data with the <a href="https://developer.mozilla.org/en-US/docs/WebRTC/MediaStream_API">MediaStream API</a>. Plus, the <code>&lt;audio&gt;</code> tag allows you to use native controls and/or provide your own customized controls.</p>

<h2>File formats</h2>

<p>Before getting in to the details on how we&rsquo;re going to use the <code>&lt;audio&gt;</code> tag, we need to talk a little about file formats. The MP3 format has gained tremendous popularity over the last decade and a half, but unfortunately due to licensing requirements, relying on MP3&rsquo;s for our audio is a messy situation.</p>

<p>Luckily for us, the <code>&lt;audio&gt;</code> tag supports multiple formats gracefully. This means we can create a patchwork of audio file formats to gain full browser support. And we&rsquo;ll need a patch work because no one format is currently supported across all browsers.</p>

<p>For our needs, we&rsquo;ve created two files: an MP4/AAC file and an OggVorbis file.</p>

<p>If you&rsquo;d like to read more on the subject, I highly recommend <a href="https://www.scirra.com/blog/44/on-html5-audio-formats-aac-and-ogg">Ashley Gullen&rsquo;s post &lsquo;On HTML5 audio formats &ndash; AAC and Ogg&rsquo;</a>.</p>

<h2>How to Use It?</h2>

<p>We can load our audio files by adding in two <code>&lt;source&gt;</code> tags with information about our two audio files inside of the <code>&lt;audio&gt;</code> tag:</p>

<figure class='code'><figcaption><span>index.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;audio</span> <span class="na">controls</span> <span class="na">id=</span><span class="s">&quot;myPlayer&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>  <span class="nt">&lt;source</span> <span class="na">src=</span><span class="s">&quot;myAudio.m4a&quot;</span> <span class="na">type=</span><span class="s">&quot;audio/mp4&quot;</span> <span class="nt">/&gt;</span>
</span><span class='line'>  <span class="nt">&lt;source</span> <span class="na">src=</span><span class="s">&quot;myAudio.ogg&quot;</span> <span class="na">type=</span><span class="s">&quot;audio/ogg&quot;</span>  <span class="nt">/&gt;</span>
</span><span class='line'>  Your browser does not support HTML5 audio.
</span><span class='line'><span class="nt">&lt;/audio&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>There are two attributes for each <code>&lt;source&gt;</code> tag. The &lsquo;src&rsquo; attribute, whose value is the path to the audio file, and the &lsquo;type&rsquo; attribute, whose value is the MIME type of the file.</p>

<p>Again, the browser will choose whichever file it supports without you having to do any detective work. Very nice.</p>

<h2>Starting/Stopping</h2>

<p>Okay, so now if we load this into a webpage we&rsquo;ll get a simple audio player that we can manually control. What&rsquo;s nice is that since we used the &lsquo;controls&rsquo; attribute, the audio player controls are built for us by the browser. This makes allowing manual control of our audio very simple.</p>

<p>For our needs, we want to control the playback of the audio programmatically. To do this, let&rsquo;s take a look at the API for starting and stopping playback. The element has two built-in methods for this, &lsquo;play&rsquo; and &lsquo;pause&rsquo;. Calling those methods is straightforward:</p>

<figure class='code'><figcaption><span>audio.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="kd">var</span> <span class="nx">audioPlayer</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">getElementById</span><span class="p">(</span><span class="s1">&#39;myPlayer&#39;</span><span class="p">);</span>
</span><span class='line'><span class="nx">audioPlayer</span><span class="p">.</span><span class="nx">play</span><span class="p">();</span>
</span><span class='line'><span class="nx">audioPlayer</span><span class="p">.</span><span class="nx">pause</span><span class="p">();</span>
</span></code></pre></td></tr></table></div></figure>


<p>These methods will come in handy in a moment when we want to start playing our audio after we change slides.</p>

<h2>Seeking</h2>

<p>The other part of the equation is the ability to seek to different locations in our audio. Again, this is very simple. Our element has a &lsquo;currentTime&rsquo; property that can be both get and set (in seconds).</p>

<figure class='code'><figcaption><span>audio.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">audioPlayer</span><span class="p">.</span><span class="nx">currentTime</span><span class="p">);</span> <span class="c1">// returns 0 since we haven&#39;t started playing the audio yet</span>
</span><span class='line'><span class="nx">audioPlayer</span><span class="p">.</span><span class="nx">currentTime</span> <span class="o">=</span> <span class="mi">10</span><span class="p">;</span> <span class="c1">// move to 10 seconds into the audio</span>
</span><span class='line'><span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">audioPlayer</span><span class="p">.</span><span class="nx">currentTime</span><span class="p">);</span> <span class="c1">// returns 10</span>
</span><span class='line'>
</span><span class='line'><span class="nx">audioPlayer</span><span class="p">.</span><span class="nx">play</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'><span class="nx">setTimeout</span><span class="p">(</span><span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
</span><span class='line'>  <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">audioPlayer</span><span class="p">.</span><span class="nx">currentTime</span><span class="p">);</span> <span class="c1">// returns 11</span>
</span><span class='line'><span class="p">},</span> <span class="mi">1000</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>As you can see, getting and setting the current time is a trivial process. In the Part 2, we&rsquo;ll put this functionality to use by adding narration to slides.</p>

<h2>Implementing Slide Narration</h2>

<p>So now we&rsquo;ve got the building blocks for implementing a slide narrator. To make things easier, we&rsquo;re going to use the fantastic <a href="http://imakewebthings.com/deck.js/">&lsquo;Deck.js&rsquo; project</a> as our HTML slide framework. Deck.js supports extensions, which allows you to add functionality to your slides beyond what&rsquo;s already provided.</p>

<p>We&rsquo;ll be creating a new extension called Narrator. For brevity&rsquo;s sake, I won&rsquo;t get into the details of Deck.js or creating extensions, but you can check out the code in <a href="https://github.com/klamping/deck.narrator.js">the deck.narrator.js GitHub repo</a>.</p>

<p>Our extension boils down to one requirement: It should automatically play a defined section of audio on each slide.</p>

<p>That might sound simple, but we need to figure out a couple of things first:</p>

<ul>
<li>How will we define what audio to play for each slide?</li>
<li>How will we stop the audio after it gets to the end of the section</li>
</ul>


<h2>Defining Audio Stops</h2>

<p>There are a couple of ways to define what segment of the audio each slide plays. You could define a start time and a stop time for each slide, but that seems like too much work. Instead we&rsquo;ll just define how long each slide should play for, and then calculate the implied start and stop timestamps for each slide.</p>

<p>To store our audio duration, we&rsquo;ll take advantage of <a href="http://ejohn.org/blog/html-5-data-attributes/">HTML5 data-* attributes</a> by creating a custom &lsquo;data-narrator-duration&rsquo; attribute. The value of this will be the number of seconds to play the audio for. Here&rsquo;s a sample slide element for a Deck.js HTML file.</p>

<figure class='code'><figcaption><span>index.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;section</span> <span class="na">class=</span><span class="s">&quot;slide&quot;</span> <span class="na">data-narrator-duration=</span><span class="s">&quot;2&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>  ...
</span><span class='line'><span class="nt">&lt;/section&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Then, upon page initialization, we&rsquo;ll loop through each slide element and calculate the proper start/stop timestamps for each slide. This is important in case our viewer wants to move through the slides in a non-linear fashion. Here&rsquo;s the basic code:</p>

<figure class='code'><figcaption><span>deck.narrator.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
<span class='line-number'>36</span>
<span class='line-number'>37</span>
<span class='line-number'>38</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="c1">// create an array for our segment timestamps </span>
</span><span class='line'><span class="kd">var</span> <span class="nx">segments</span> <span class="o">=</span> <span class="p">[];</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// create a placeholder for our audio element reference </span>
</span><span class='line'><span class="kd">var</span> <span class="nx">audio</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// we&#39;ll get to this variable later</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">segmentEnd</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'><span class="kd">function</span> <span class="nx">init</span> <span class="p">()</span> <span class="p">{</span>
</span><span class='line'>  <span class="c1">// get the audio element we added to our page</span>
</span><span class='line'>  <span class="nx">audio</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">getElementById</span><span class="p">(</span><span class="s1">&#39;audioNarration&#39;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// use deck.js built-in functionality to get all slides and current slide</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">$slides</span> <span class="o">=</span> <span class="nx">$</span><span class="p">.</span><span class="nx">deck</span><span class="p">(</span><span class="s1">&#39;getSlides&#39;</span><span class="p">);</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">$currentSlide</span> <span class="o">=</span> <span class="nx">$</span><span class="p">.</span><span class="nx">deck</span><span class="p">(</span><span class="s1">&#39;getSlide&#39;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// set initial values for time position and index</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">position</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">currentIndex</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// now loop through each slide</span>
</span><span class='line'>  <span class="nx">$</span><span class="p">.</span><span class="nx">each</span><span class="p">(</span><span class="nx">$slides</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">i</span><span class="p">,</span> <span class="nx">$el</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="c1">// get the duration specified from the HTML element</span>
</span><span class='line'>    <span class="kd">var</span> <span class="nx">duration</span> <span class="o">=</span> <span class="nx">$el</span><span class="p">.</span><span class="nx">data</span><span class="p">(</span><span class="s1">&#39;narrator-duration&#39;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>    <span class="c1">// this determines which slide the viewer loaded the page on</span>
</span><span class='line'>    <span class="k">if</span> <span class="p">(</span><span class="nx">$currentSlide</span> <span class="o">==</span> <span class="nx">$el</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>      <span class="nx">currentIndex</span> <span class="o">=</span> <span class="nx">i</span><span class="p">;</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="c1">// push the start time (previous position) and end time (position + duration) to an array of slides</span>
</span><span class='line'>    <span class="nx">segments</span><span class="p">.</span><span class="nx">push</span><span class="p">([</span><span class="nx">position</span><span class="p">,</span> <span class="nx">position</span> <span class="o">+</span> <span class="nx">duration</span><span class="p">]);</span>
</span><span class='line'>
</span><span class='line'>    <span class="c1">// increment the position to the start of the next slide</span>
</span><span class='line'>    <span class="nx">position</span> <span class="o">+=</span> <span class="nx">duration</span><span class="p">;</span>
</span><span class='line'>  <span class="p">});</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Adding Playback Automatically on Slide Change</h2>

<p>Now that we&rsquo;ve got our segment timestamps defined, let&rsquo;s look at playing that audio on each slide transition. Deck.js fires a &lsquo;deck.change&rsquo; event when the slide is changed, so we can hook into that and have it call our changeSlides function, which looks like this:</p>

<figure class='code'><figcaption><span>deck.narrator.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="kd">function</span> <span class="nx">changeSlides</span> <span class="p">(</span><span class="nx">e</span><span class="p">,</span> <span class="nx">from</span><span class="p">,</span> <span class="nx">to</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="c1">// check to make sure audio element has been found</span>
</span><span class='line'>  <span class="k">if</span><span class="p">(</span><span class="nx">audio</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="c1">// move the playback to our slides start</span>
</span><span class='line'>    <span class="nx">audio</span><span class="p">.</span><span class="nx">currentTime</span> <span class="o">=</span> <span class="nx">segments</span><span class="p">[</span><span class="nx">to</span><span class="p">][</span><span class="mi">0</span><span class="p">];</span>
</span><span class='line'>
</span><span class='line'>    <span class="c1">// define the end of our section</span>
</span><span class='line'>    <span class="nx">segmentEnd</span> <span class="o">=</span> <span class="nx">segments</span><span class="p">[</span><span class="nx">to</span><span class="p">][</span><span class="mi">1</span><span class="p">];</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Most of the code makes sense, but I do want to talk about the &lsquo;segmentEnd&rsquo; line and what it&rsquo;s doing.</p>

<h2>Playing Segments of Audio</h2>

<p>Unfortunately, you can&rsquo;t give the <code>play()</code> function an amount of time to play for. Once you start playing, it will keep going until it runs out of audio or you tell it to pause. Thankfully, the audio element emits a &lsquo;timeupdate&rsquo; event which we can listen to in order to pause playback once our segment timestamp has been reached. We can add that listener just like any other event listener:</p>

<figure class='code'><figcaption><span>deck.narrator.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nx">audio</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">&#39;timeupdate&#39;</span><span class="p">,</span> <span class="nx">checkTime</span><span class="p">,</span> <span class="kc">false</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>Our &lsquo;checkTime&rsquo; function is very small. All it does is check to see if currentTime in the audio is greater than the segmentEnd time. If so, it pauses our audio:</p>

<figure class='code'><figcaption><span>deck.narrator.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="kd">function</span> <span class="nx">checkTime</span> <span class="p">()</span> <span class="p">{</span>
</span><span class='line'>  <span class="k">if</span> <span class="p">(</span><span class="nx">audio</span><span class="p">.</span><span class="nx">currentTime</span> <span class="o">&gt;=</span> <span class="nx">segmentEnd</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">audio</span><span class="p">.</span><span class="nx">pause</span><span class="p">();</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Automatically Moving Through Slides</h2>

<p>Now that we&rsquo;ve got our audio hooked up to our slides, we can take advantage of the other extensions already written for Deck.js. <a href="deck.automatic.js">https://github.com/rchampourlier/deck.automatic.js/‎</a> is an extension that makes your slides run automatically. By including this extension with our presentation, we can recreate that &lsquo;presentation&rsquo; feel to our slides.</p>

<p>Aside from the going through the steps of adding the automatic extension, we also need to make sure that if a user starts/stops the audio, we start/stop the slideshow playback. To do this, we&rsquo;ll sync up <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/Events/Media_events">the &lsquo;play&rsquo; and &lsquo;pause&rsquo; events of our audio element</a> with the automatic extension. For simplicity, we&rsquo;re going to control all slide playback using our audio controls and leave off the deck.automatic.js playback control.</p>

<p>Deck.automatic.js adds some events to the mix, including &lsquo;play&rsquo; and &lsquo;pause&rsquo; events. By triggering these events when our similarly named audio events fire, we can make sure our slides are in sync with our content.</p>

<p>We add two simple functions to our extension:</p>

<figure class='code'><figcaption><span>deck.narrator.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="kd">function</span> <span class="nx">startSlides</span> <span class="p">(</span><span class="nx">ev</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="nx">$</span><span class="p">.</span><span class="nx">deck</span><span class="p">(</span><span class="s1">&#39;play&#39;</span><span class="p">);</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="kd">function</span> <span class="nx">stopSlides</span> <span class="p">(</span><span class="nx">ev</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="nx">$</span><span class="p">.</span><span class="nx">deck</span><span class="p">(</span><span class="s1">&#39;pause&#39;</span><span class="p">);</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>And then add our event listeners in the deck.init callback:</p>

<figure class='code'><figcaption><span>deck.narrator.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nx">$d</span><span class="p">.</span><span class="nx">bind</span><span class="p">(</span><span class="s1">&#39;deck.init&#39;</span><span class="p">,</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// ... other code here ...</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// Sync audio with slides</span>
</span><span class='line'>  <span class="nx">audio</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">&#39;play&#39;</span><span class="p">,</span> <span class="nx">startSlides</span><span class="p">,</span> <span class="kc">false</span><span class="p">);</span>
</span><span class='line'>  <span class="nx">audio</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">&#39;pause&#39;</span><span class="p">,</span> <span class="nx">stopSlides</span><span class="p">,</span> <span class="kc">false</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p>Also, since our slides automatically advance, we need to comment out the &lsquo;timeupdate&rsquo; event listener which would pause our audio at the end of a slide.</p>

<p>With those things taken care of, our slides and audio automatically transition to create a seamless experience.</p>

<h2>Next Steps</h2>

<p>One thing the code doesn&rsquo;t take into consideration is if the user navigation the audio themselves. We could add this by listening to the &lsquo;seeked&rsquo; event from the audio element and calculating where in the slide deck we should move to.</p>

<p>There is also some duplication around defining the duration of the as a result of adding in the automatic slide advancement extension. The other extension is looking for a data-duration attribute on each slide. This can be easily fixed by updating our code to look for that attribute instead.</p>

<p>Finally, we need to add in some captioning for folks who either cannot hear the audio or are in a public place and simply forgot their headphones. There is <a href="http://www.w3.org/wiki/HTML/Elements/track">a new <code>track</code> tag</a> that can handle this for us, so that&rsquo;s a likely route we can go down.</p>

<h2>Summing Up</h2>

<p>That&rsquo;s the majority of the code. I left out a few details in relation to some deck.js configurations, so again check out <a href="https://github.com/klamping/deck.narrator.js">the GitHub repo for the full example</a>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Ember.js Views and Live Templates with Handlebars.js Part 1]]></title>
    <link href="http://html5hacks.com/blog/2013/06/04/ember-dot-js-views-and-live-templates-with-handlebars-dot-js-part-1/"/>
    <updated>2013-06-04T11:05:00-05:00</updated>
    <id>http://html5hacks.com/blog/2013/06/04/ember-dot-js-views-and-live-templates-with-handlebars-dot-js-part-1</id>
    <content type="html"><![CDATA[<p><img class="imgL" alt="Tech-pro Ember.js Views" src="http://tpstatic.com/img/usermedia/cHI1WdevsEyBJ7dLfmVUdA/cropped-w220-h220.png"></p>

<p>This is an exploration of Handlebars.js template library when used with Ember.js views. Many of the Handlebars.js tutorials on the web discuss the Handlebars API, but not in the specific context of using Handlebars with Ember.js. In addition to filling that void, I&rsquo;ll also give a brief background of JavaScript templating in general to provide perspective as to the problems it is solving.</p>

<p>This tutorial will be divided into two parts. In Part 1, you should gain a clear understanding of JavaScript templates, the capabilities of Handlebars expressions and helpers, and how to write your own Handlebars helpers.</p>

<p>Read more at: <a href="http://tech.pro/tutorial/1308/emberjs-views-and-live-templates-with-handlebarsjs-part-1">http://tech.pro/tutorial/1308/emberjs-views-and-live-templates-with-handlebarsjs-part-1</a></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Utilize Rich Input Data from W3C Pointer Events]]></title>
    <link href="http://html5hacks.com/blog/2013/05/13/rich-input-data-from-w3c-pointer-events/"/>
    <updated>2013-05-13T01:42:00-05:00</updated>
    <id>http://html5hacks.com/blog/2013/05/13/rich-input-data-from-w3c-pointer-events</id>
    <content type="html"><![CDATA[<p>The W3C Pointer Events specification allows you to develop for a single event model that supports various input types.  Instead of writing code for multiple event types, or having to use feature detection on page load that forces one event model over the other, Pointers allows you to write one event model that works everywhere.  To make the transition easy, Pointer Events builds upon the Event Model of Mouse Events.  This means that code that’s written for mouse events is going to be very easy to upgrade to Pointers.</p>

<p>There’s a lot of great content out there on how to implement pointers.  Microsoft’s original post on pointer event implementation in IE10 and Windows 8 Apps is a great place to start learning about Pointers.  To see an example of how to convert a current mouse based app into a pointers based app, I suggest you check out my channel 9 video on pointers. In this post I want to focus on a different aspect of pointers.  Along with the multiple input support, and ease of implementation, Pointer Events also provide a wealth of new data values that can be quite useful in your applications.  This post will look in depth at that data.</p>

<p>The code samples will all use the W3C spec pointer names such as “pointermove” and “pointerup”, however in practice this spec is not finalized, so the working code samples will be using the prefixed version such as “MSPointerMove” and “MSPointerUp”.</p>

<h2>The Pointer Event Object</h2>

<p>The Pointer Event object is modeled directly off the Mouse Event object, meaning all the values, and all the methods available in a mouse event model, will be present inside a Pointer Event Model.  Let’s look at an example you might implement for the Mouse Event Model:</p>

<figure class='code'><figcaption><span>More poiner.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>        <span class="kd">var</span> <span class="nx">myY</span><span class="p">,</span> <span class="nx">myX</span><span class="p">;</span>
</span><span class='line'>        <span class="nb">document</span><span class="p">.</span><span class="nx">getElementById</span><span class="p">(</span><span class="s1">&#39;myElement&#39;</span><span class="p">).</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">&#39;mouseup&#39;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">){</span>
</span><span class='line'>
</span><span class='line'>            <span class="nx">e</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'>            <span class="nx">myY</span> <span class="o">=</span> <span class="nx">e</span><span class="p">.</span><span class="nx">offsetY</span><span class="p">;</span>
</span><span class='line'>            <span class="nx">myX</span> <span class="o">=</span> <span class="nx">e</span><span class="p">.</span><span class="nx">offsetX</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>        <span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p>This same code will also run with Pointer Events:</p>

<figure class='code'><figcaption><span>More poiner.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>        <span class="nb">document</span><span class="p">.</span><span class="nx">getElementById</span><span class="p">(</span><span class="s1">&#39;myElement&#39;</span><span class="p">).</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">&#39;pointerup&#39;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">){</span>
</span><span class='line'>
</span><span class='line'>            <span class="nx">e</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'>            <span class="nx">myY</span> <span class="o">=</span> <span class="nx">e</span><span class="p">.</span><span class="nx">offsetY</span><span class="p">;</span>
</span><span class='line'>            <span class="nx">myX</span> <span class="o">=</span> <span class="nx">e</span><span class="p">.</span><span class="nx">offsetX</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>        <span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p>Every value and method will run the same.  The main difference is that Pointers aren’t single threaded as Mouse Events are (you can only have one mouse pointer on the screen at a time).  So if you have two Pointers on the screen, say two fingers on your touch screen, or one finger and one mouse, this event will be fired twice.</p>

<p>The “upgrade” comes in all the additional data that is available when you use Pointer Events.</p>

<h2>The Event Type</h2>

<p>Since a Pointer Event will be fired no matter what type of input you are using, it’s sometimes important to know what type of input is firing the Event. While accessing the event object, you can retrieve the pointer type like so:</p>

<figure class='code'><figcaption><span>More poiner.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>        <span class="nb">document</span><span class="p">.</span><span class="nx">getElementById</span><span class="p">(</span><span class="s1">&#39;myElement&#39;</span><span class="p">).</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">&#39;pointerup&#39;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">){</span>
</span><span class='line'>
</span><span class='line'>            <span class="kd">var</span> <span class="nx">pointerType</span> <span class="o">=</span> <span class="nx">e</span><span class="p">.</span><span class="nx">pointerType</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>        <span class="p">});</span>
</span><span class='line'>
</span></code></pre></td></tr></table></div></figure>


<p>The type will return one of three value types:</p>

<p>-mouse: movement with a mouse
-pen: movement with a pressure sensitive pen (not a capacitive stylus)
-touch: any input from the touch screen</p>

<p>Note that the original spec, and what is implemented In IE10, provides number values that correspond with the input types.  The value will return either a 2(touch), 3(pen) or 4(mouse).</p>

<p>For implementing pointers today, I actually check for both the string value or the number to be sure I support both the current implementation and the final spec:</p>

<figure class='code'><figcaption><span>More poiner.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>        <span class="nb">document</span><span class="p">.</span><span class="nx">getElementById</span><span class="p">(</span><span class="s1">&#39;myElement&#39;</span><span class="p">).</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">&#39;pointerup&#39;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">){</span>
</span><span class='line'>
</span><span class='line'>            <span class="kd">var</span> <span class="nx">pointerType</span> <span class="o">=</span> <span class="nx">e</span><span class="p">.</span><span class="nx">pointerType</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>            <span class="k">if</span> <span class="p">(</span><span class="nx">pointerType</span> <span class="o">==</span> <span class="s1">&#39;touch&#39;</span><span class="o">||</span><span class="mi">4</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>                <span class="c1">//this is a touch type pointer</span>
</span><span class='line'>            <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>        <span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<h2>New Values for All Pointer Types</h2>

<p>There is a range of new values packed into the Pointer Event Object that is common across all pointer types.  Each of these expose new values that provide valuable data for interaction development</p>

<p><em>PointerID:</em> each pointer interaction is given a unique ID within your page and session.  This number will be consistent across events for each interaction.  For Example, a “pointerdown” event may be given a PointerID of 127, the subsequent “pointermove” and “pointerend” events will all have the same PointerID.  This could be helpful for tracking which finger is doing what when there are multiple touch screen pointers on the screen at once.  You can access the value as below:</p>

<figure class='code'><figcaption><span>More poiner.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>        <span class="nb">document</span><span class="p">.</span><span class="nx">getElementById</span><span class="p">(</span><span class="s1">&#39;myElement&#39;</span><span class="p">).</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">&#39;pointerdown&#39;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">){</span>
</span><span class='line'>
</span><span class='line'>            <span class="kd">var</span> <span class="nx">pointerId</span> <span class="o">=</span> <span class="nx">e</span><span class="p">.</span><span class="nx">pointerId</span>
</span><span class='line'>            <span class="p">;</span>
</span><span class='line'>        <span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p><em>isPrimary:</em> When multiple Pointer Events are on the screen at once, one of them will be assigned as the primary pointer.  If one of them is of the Pointer type of mouse, it will be the primary, otherwise the first pointer to fire an event will be designated as the primary.  This could be helpful for a developer who is building an application that is intended for a single pointer input.  There is one catch, when you are using multiple pointer types on the screen at the same time, the first pointer of each type will be a primary pointer, and thus will allow you to have multiple primary pointers on the screen at the same time.  The value can be accessed as such:</p>

<figure class='code'><figcaption><span>More poiner.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>        <span class="nb">document</span><span class="p">.</span><span class="nx">getElementById</span><span class="p">(</span><span class="s1">&#39;myElement&#39;</span><span class="p">).</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">&#39;pointerup&#39;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">){</span>
</span><span class='line'>
</span><span class='line'>            <span class="kd">var</span> <span class="nx">isPrimary</span> <span class="o">=</span> <span class="nx">e</span><span class="p">.</span><span class="nx">isPrimary</span><span class="p">;</span> <span class="c1">// will return true or false</span>
</span><span class='line'>
</span><span class='line'>        <span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p><em>button/buttons:</em> This isn’t a new value for pointers, but in pointers you get new information.  With both a mouse and a pen, the user has buttons that can be pressed. Weather those buttons are being pressed, and which button is pressed can be determined in these two values.</p>

<p><img class="figure" alt="Figure 12-1" src="http://html5hacks.com/images/chapter-jeff/buttonChart.png"></p>

<p>The entire list of values can be found in the most recent version of the spec, and keep in mind, not all values are implemented in IE10 (or any other browser) at this point.</p>

<h2>Pen Specific Values</h2>

<p>There are some values that are only applicable to the pointer type of Pen.  Keep in mind the pen type refers to a mechanical stylus that works with supported screen types.  Capacitive styus like the types used with iPads or Surface RT register as pointer types of touch, which will be discussed next.</p>

<p>The following values provide data in the Pointer Event Object for pens:</p>

<p><em>tiltX/tiltY:</em> When you hold a pen there is generally an angle associated with it.  If you were to hold the pen by the end and lower it perfectly straight on the screen, the tilt would be 0, but if you were to hold it in writing position, it would have a tilt value like 90.  The tilt values are returned in degrees and be accessed as such:</p>

<figure class='code'><figcaption><span>More poiner.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nb">document</span><span class="p">.</span><span class="nx">getElementById</span><span class="p">(</span><span class="s1">&#39;myElement&#39;</span><span class="p">).</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">&#39;pointerup&#39;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">){</span>
</span><span class='line'>
</span><span class='line'>
</span><span class='line'>            <span class="kd">var</span> <span class="nx">tiltX</span> <span class="o">=</span> <span class="nx">e</span><span class="p">.</span><span class="nx">tiltX</span><span class="p">;</span>
</span><span class='line'>            <span class="kd">var</span> <span class="nx">tiltY</span> <span class="o">=</span> <span class="nx">e</span><span class="p">.</span> <span class="nx">tiltY</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>        <span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p><em>Pressure:</em>  Much of the data provided from a pen type pointer event is actually data provided from the pen to the screen.  Another one of those is pressure.  This is a value that reports how hard a pen is being pressed against the screen.  The value is reported as a number between x and x.  The value is accessed as below:</p>

<figure class='code'><figcaption><span>More poiner.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nb">document</span><span class="p">.</span><span class="nx">getElementById</span><span class="p">(</span><span class="s1">&#39;myElement&#39;</span><span class="p">).</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">&#39;pointerup&#39;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">){</span>
</span><span class='line'>
</span><span class='line'>
</span><span class='line'>            <span class="kd">var</span> <span class="nx">pressure</span> <span class="o">=</span> <span class="nx">e</span><span class="p">.</span><span class="nx">pressure</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>        <span class="p">});</span>
</span><span class='line'>
</span></code></pre></td></tr></table></div></figure>


<h2>New Data for Touch</h2>

<p>The Pointer Spec provides for detail touch data that just doesn’t exist in any other touch model on the web.  Most significantly the actual width and height of a the touch area.  Being so new, my testing showed that this value is often returned as 0 depending on the touch screen and driver installed on the device.  Accessing this data follows the same patteren as the other new data:</p>

<figure class='code'><figcaption><span>More poiner.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nb">document</span><span class="p">.</span><span class="nx">getElementById</span><span class="p">(</span><span class="s1">&#39;myElement&#39;</span><span class="p">).</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">&#39;pointerup&#39;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">){</span>
</span><span class='line'>
</span><span class='line'>
</span><span class='line'>            <span class="kd">var</span> <span class="nx">width</span> <span class="o">=</span> <span class="nx">e</span><span class="p">.</span><span class="nx">width</span><span class="p">;</span>
</span><span class='line'>            <span class="kd">var</span> <span class="nx">height</span> <span class="o">=</span> <span class="nx">e</span><span class="p">.</span><span class="nx">height</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>        <span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p>Keep in mind this is related to touch pointers only, so a mouse or pen will always return 0 for these values.</p>

<h2>Mobile Implementations</h2>

<p>The only mobile browser that has implemented Pointers is IE10 for Windows Phone 8.  Since the phone OS doesn’t support a mouse or mechanical stylus, the only pointer type that returns is touch.  The user agent does accurately report the pointer type, but many of the other new pointer values (such as width and height) are currently reported as 0s.</p>

<h2>The Sample App</h2>

<p>I’ve been working on a sample app that helps illustrate the rich data reported through pointers.  It’s a simple canvas resized to your page that shows a report from each touch point of the key data values, additionally, the new data is used to effect the drawing on the screen to make a more accurate drawing surface.</p>

<p>Test the app here in IE 10 or any future browser that supports pointer events, or view this video of the app in action.</p>

<h2>Next Steps</h2>

<p>The Pointer Event Specification is not yet finalized so changes could occur at any time (and it has changed since the version implemented in ie10). If you interested in the work that is going on around Pointers, join the working group mailing list, and encourage others in the browser maker community to implement the Pointer Even Specification in every browser.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Push Notifications to the Browser with Server Sent Events]]></title>
    <link href="http://html5hacks.com/blog/2013/04/21/push-notifications-to-the-browser-with-server-sent-events/"/>
    <updated>2013-04-21T15:44:00-05:00</updated>
    <id>http://html5hacks.com/blog/2013/04/21/push-notifications-to-the-browser-with-server-sent-events</id>
    <content type="html"><![CDATA[<p>Created by Opera, Server Sent Events standardizes Comet technologies. The standard intends to enable native real time updates through a simple JavaScript API called EventSource, which connects to servers that asynchronously push data updates to clients via HTTP Streaming. Server Sent Events use a single, unidirectional, persistent connection between the browser and the server.</p>

<p>Unlike the Web Socket API, Server Sent Events and EventSource object use HTTP to enable real-time server push capabilities within your application. HTTP Streaming predates the WebSocket API, and it is often referred to as Comet or server push. The exciting part here is that the Server Sent Events API intends to standardize the Comet technique, making it trivial to implement in the browser.</p>

<h2>What is HTTP Streaming?</h2>

<p>In a standard HTTP request and response between a web browser and a web server, the server will close the connection once it has completed the processing of the request. HTTP streaming, or Comet, differs in that the server maintains a persistent, open connection with the browser.</p>

<p>It is important to note that not all web servers are capable of streaming. Only evented servers such as Node.js, Tornado, or Thin are equipped incorporate an event loop that is optimal for supporting HTTP streaming. These, non-blocking servers handle persistent connections from a large number of concurrent requests very well.</p>

<p>A complete discussion on evented vs. threaded servers is out of scope for this post, but that being said, in the upcoming hack we will provide a very simple evented server implementation example to get you started. We provide a simple browser based JavaScript to connect to the server, and a server side implementation using Ruby, Thin, and Sinatra.
For the record, this is also very easy to do with Node.js.</p>

<p>Here is a link to the companion github repository:
<a href="https://github.com/html5hacks/chapter9">https://github.com/html5hacks/chapter9</a></p>

<h2>Ruby’s Sinatra</h2>

<p>The Sinatra documentation describes itself as a “DSL for quickly creating web applications in Ruby with minimal effort.”
This text has focused primarily on Node.js (HTTP Server) and Express.js (web application framework) to quickly generate server side implementations for hacking out functionality.</p>

<p>It would a disservice to not mention Ruby, Rails and Sinatra in the same or similar light as we have Node.js in this text. Although learning Ruby is another learning curve, in the larger scheme of programming languages it is a less daunting curve than most. And as most die-hard Rubyists will preach, it is arguably the most elegant and fun to write of all modern programming languages. Ruby on Rails, and its little brother Sinatra are also great web application frameworks to start with if you are new to web application development.</p>

<p>Much like Node.js and Express, Sinatra makes building small server implementations nearly trivial. So for the context of HTML5 Hacks, that allows us to focus our efforts on programming in the browser.</p>

<p>For now let’s build a simple HTTP Streaming server using Sinatra.</p>

<p>To get started with Ruby On Rails or Sinatra, check out the great documentation available at <a href="http://guides.rubyonrails.org/getting_started.html">http://guides.rubyonrails.org/getting_started.html</a> and <a href="http://sinatrarb.com/intro">http://sinatrarb.com/intro</a>, respectively.</p>

<h2>Building Push Notifications</h2>

<p>Our goal in the next hack is to build a simple streaming server and use the EventSource object to open a persistent connection from the browser. We will then push notifcations from one ‘admin’ browser to all the connected receivers. Sounds simple, right? Let’s get started.</p>

<h2>A Simple HTTP Streaming Server</h2>

<p>Open up a file and name it stream.rb. Then add the following:
Simple requiring of Sinatra and the JSON library:</p>

<figure class='code'><figcaption><span>stream.rb </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='rb'><span class='line'>  <span class="nb">require</span> <span class="s1">&#39;json&#39;</span>
</span><span class='line'>  <span class="nb">require</span> <span class="s1">&#39;sinatra&#39;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Then, we set up a public folder, and set the server to use the evented ruby server, Thin.</p>

<figure class='code'><figcaption><span>stream.rb </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='rb'><span class='line'>  <span class="n">set</span> <span class="ss">:public_folder</span><span class="p">,</span> <span class="no">Proc</span><span class="o">.</span><span class="n">new</span> <span class="p">{</span> <span class="no">File</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">root</span><span class="p">,</span> <span class="s2">&quot;public&quot;</span><span class="p">)</span> <span class="p">}</span>
</span><span class='line'>  <span class="n">set</span> <span class="ss">server</span><span class="p">:</span> <span class="s1">&#39;thin&#39;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Set up two routs for serving our 2 pages: index and admin. We will use Erb as our templating language. The details are out of scope, but our use is very minimal. More on Erb here: <a href="http://ruby-doc.org/stdlib-1.9.3/libdoc/erb/rdoc/ERB.html">http://ruby-doc.org/stdlib-1.9.3/libdoc/erb/rdoc/ERB.html</a></p>

<figure class='code'><figcaption><span>stream.rb </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='rb'><span class='line'>  <span class="n">get</span> <span class="s1">&#39;/&#39;</span> <span class="k">do</span>
</span><span class='line'>    <span class="n">erb</span> <span class="ss">:index</span>
</span><span class='line'>  <span class="k">end</span>
</span><span class='line'>
</span><span class='line'>  <span class="n">get</span> <span class="s1">&#39;/admin&#39;</span> <span class="k">do</span>
</span><span class='line'>    <span class="n">erb</span> <span class="ss">:admin</span>
</span><span class='line'>  <span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>We’d like to timestamp each notification, so here is a very simple function definition.</p>

<figure class='code'><figcaption><span>stream.rb </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='rb'><span class='line'>  <span class="k">def</span> <span class="nf">timestamp</span>
</span><span class='line'>    <span class="no">Time</span><span class="o">.</span><span class="n">now</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s2">&quot;%H:%M:%S&quot;</span><span class="p">)</span>
</span><span class='line'>  <span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>We also set up two empty arrays: one to hold the connections and the other to hold out notifications.</p>

<figure class='code'><figcaption><span>stream.rb </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='rb'><span class='line'>  <span class="n">connections</span> <span class="o">=</span> <span class="o">[]</span>
</span><span class='line'>  <span class="n">notifications</span> <span class="o">=</span> <span class="o">[]</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now, for the routes. When our browser loads it s page, we have JavaScript running which will use the EventSource object to connect to a url here: <a href="http://localhost:4567/connect.">http://localhost:4567/connect.</a></p>

<p>More on EventSource later.</p>

<p>But for now you can see the magic of the evented HTTP stream, the connection is held open until a callback is fired to close the stream.</p>

<figure class='code'><figcaption><span>stream.rb </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='rb'><span class='line'>  <span class="n">get</span> <span class="s1">&#39;/connect&#39;</span><span class="p">,</span> <span class="ss">provides</span><span class="p">:</span> <span class="s1">&#39;text/event-stream&#39;</span> <span class="k">do</span>
</span><span class='line'>    <span class="n">stream</span> <span class="ss">:keep_open</span> <span class="k">do</span> <span class="o">|</span><span class="n">out</span><span class="o">|</span>
</span><span class='line'>      <span class="n">connections</span> <span class="o">&lt;&lt;</span> <span class="n">out</span>
</span><span class='line'>
</span><span class='line'>      <span class="c1">#out.callback on stream close evt. </span>
</span><span class='line'>      <span class="n">out</span><span class="o">.</span><span class="n">callback</span> <span class="p">{</span>
</span><span class='line'>        <span class="c1">#delete the connection </span>
</span><span class='line'>        <span class="n">connections</span><span class="o">.</span><span class="n">delete</span><span class="p">(</span><span class="n">out</span><span class="p">)</span>
</span><span class='line'>      <span class="p">}</span>
</span><span class='line'>    <span class="k">end</span>
</span><span class='line'>  <span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>Finally, any data this posted to the /push route is pushed out to each connected device.</p>

<figure class='code'><figcaption><span>stream.rb </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='rb'><span class='line'>  <span class="n">post</span> <span class="s1">&#39;/push&#39;</span> <span class="k">do</span>
</span><span class='line'>    <span class="nb">puts</span> <span class="n">params</span>
</span><span class='line'>    <span class="c1">#Add the timestamp to the notification</span>
</span><span class='line'>    <span class="n">notification</span> <span class="o">=</span> <span class="n">params</span><span class="o">.</span><span class="n">merge</span><span class="p">(</span> <span class="p">{</span><span class="s1">&#39;timestamp&#39;</span> <span class="o">=&gt;</span> <span class="n">timestamp</span><span class="p">})</span><span class="o">.</span><span class="n">to_json</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">notifications</span> <span class="o">&lt;&lt;</span> <span class="n">notification</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">notifications</span><span class="o">.</span><span class="n">shift</span> <span class="k">if</span> <span class="n">notifications</span><span class="o">.</span><span class="n">length</span> <span class="o">&gt;</span> <span class="mi">10</span>
</span><span class='line'>    <span class="n">connections</span><span class="o">.</span><span class="n">each</span> <span class="p">{</span> <span class="o">|</span><span class="n">out</span><span class="o">|</span> <span class="n">out</span> <span class="o">&lt;&lt;</span> <span class="s2">&quot;data: </span><span class="si">#{</span><span class="n">notification</span><span class="si">}</span><span class="se">\n\n</span><span class="s2">&quot;</span><span class="p">}</span>
</span><span class='line'>  <span class="k">end</span>
</span></code></pre></td></tr></table></div></figure>


<p>As we said before, you can just follow the instructions at our git repository to pull down and build this code. Or if you have been following along, launch a terminal, navigate to the directory where you code is, and run:</p>

<figure class='code'><figcaption><span>cli </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>$ ruby stream.rb</span></code></pre></td></tr></table></div></figure>


<p>Figure 9.15 Starting the Sinatra Server</p>

<p><img class="figure" alt="Figure 7-2" src="http://html5hacks.com/images/chapter9-images/9-15.png"></p>

<p>Alright, so now that we have out Sinatra app up and running with custom routes to handle incoming requests from our browser.</p>

<p>If this doesn’t make complete sense yet, just hang loose. In the upcoming subsections, the rest of the items will start to fall into place.</p>

<h2>Set Up the HTML pages</h2>

<p>We will be building 2 pages: one for the admin to push out notifications, and the other will be for the connected receivers to receive the notification. Both of these ‘views’ will share the same layout, as such:</p>

<figure class='code'><figcaption><span>index.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;html&gt;</span>
</span><span class='line'>  <span class="nt">&lt;head&gt;</span>
</span><span class='line'>    <span class="nt">&lt;title&gt;</span>HTML5 Hacks - Server Sent Events<span class="nt">&lt;/title&gt;</span>
</span><span class='line'>    <span class="nt">&lt;meta</span> <span class="na">charset=</span><span class="s">&quot;utf-8&quot;</span> <span class="nt">/&gt;</span>
</span><span class='line'>
</span><span class='line'>    <span class="nt">&lt;script </span><span class="na">src=</span><span class="s">”http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js”</span><span class="nt">&gt;</span>
</span><span class='line'><span class="nt">&lt;/script&gt;</span>
</span><span class='line'>    <span class="nt">&lt;script </span><span class="na">src=</span><span class="s">&quot;http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.js&quot;</span><span class="nt">&gt;</span> <span class="nt">&lt;/script&gt;</span>
</span><span class='line'>    <span class="nt">&lt;script </span><span class="na">src=</span><span class="s">&quot;jquery.notify.js&quot;</span> <span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'>    <span class="nt">&lt;link</span> <span class="na">rel=</span><span class="s">&quot;stylesheet&quot;</span> <span class="na">type=</span><span class="s">&quot;text/css&quot;</span> <span class="na">href=</span><span class="s">&quot;style.css&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>    <span class="nt">&lt;link</span> <span class="na">rel=</span><span class="s">&quot;stylesheet&quot;</span> <span class="na">type=</span><span class="s">&quot;text/css&quot;</span> <span class="na">href=</span><span class="s">&quot;ui.notify.css&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>
</span><span class='line'>  <span class="nt">&lt;/head&gt;</span>
</span><span class='line'>  <span class="nt">&lt;body&gt;</span>
</span><span class='line'>    <span class="cp">&lt;!—- implementation specific here --&gt;</span>
</span><span class='line'>  <span class="nt">&lt;/body&gt;</span>
</span><span class='line'><span class="nt">&lt;/html&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>The admin page will contain an input tag and a simple button.</p>

<figure class='code'><figcaption><span>admin.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;div</span> <span class="na">id=</span><span class="s">&quot;wrapper&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>    <span class="nt">&lt;input</span> <span class="na">type=</span><span class="s">&quot;text&quot;</span> <span class="na">id=</span><span class="s">&quot;message&quot;</span> <span class="na">placeholder=</span><span class="s">&quot;Enter Notification Here&quot;</span> <span class="nt">/&gt;&lt;br&gt;</span>
</span><span class='line'>    <span class="nt">&lt;input</span> <span class="na">type=</span><span class="s">”button”</span> <span class="na">id=</span><span class="s">&quot;send&quot;</span> <span class="na">data-role=</span><span class="s">&quot;button&quot;</span><span class="nt">&gt;</span>push<span class="nt">&lt;/input&gt;</span>
</span><span class='line'><span class="nt">&lt;/div&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>And our receiver pages will display a simple piece of text:</p>

<figure class='code'><figcaption><span>receiver.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;div</span> <span class="na">id=</span><span class="s">&quot;wrapper&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>  <span class="nt">&lt;p&gt;</span>Don&#39;t Mind me ... Just Waiting for a Push Notification from HTML5 Hacks.<span class="nt">&lt;/p&gt;</span>
</span><span class='line'><span class="nt">&lt;/div&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>By launching one browser window to <a href="http://localhost:4567/admin">http://localhost:4567/admin</a> you should now see our admin form.</p>

<p>Figure 9.16 The initial admin page</p>

<p><img class="figure" alt="Figure 9-16" src="http://html5hacks.com/images/chapter9-images/9-16.png"></p>

<p>And, navigate to <a href="http://localhost:4567">http://localhost:4567</a> in your browser and you should see.</p>

<p>Figure 9.17 The initial index page</p>

<p><img class="figure" alt="Figure 9-17" src="http://html5hacks.com/images/chapter9-images/9-17.png"></p>

<h2>Adding a bit of jQuery</h2>

<p>We need to add a bit of JavaScript to attach an event listener to the “send” button. This snippet will prevent the default submission of the form and post the notifcation object to the server as JSON.
Notice the url /push maps to the route we defined in our Sinatra app.</p>

<figure class='code'><figcaption><span>push.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'> <span class="nx">$</span><span class="p">(</span><span class="s1">&#39;#send&#39;</span><span class="p">).</span><span class="nx">click</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">event</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'>   <span class="kd">var</span> <span class="nx">notifcation</span> <span class="o">=</span> <span class="p">{</span> <span class="nx">notifcation</span><span class="o">:</span> <span class="nx">$</span><span class="p">(</span><span class="s1">&#39;#notification&#39;</span><span class="p">).</span><span class="nx">val</span><span class="p">()};</span>
</span><span class='line'>
</span><span class='line'>    <span class="nx">$</span><span class="p">.</span><span class="nx">post</span><span class="p">(</span> <span class="s1">&#39;/push&#39;</span><span class="p">,</span> <span class="nx">notifcation</span><span class="p">,</span><span class="s1">&#39;json&#39;</span><span class="p">);</span>
</span><span class='line'> <span class="p">})</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now, lets open up five browser windows: one admin at <a href="http://localhost:4567/admin">http://localhost:4567/admin</a> and four more receivers at <a href="http://localhost:4567">http://localhost:4567</a></p>

<p>Figure 9.18 Opening 5 browser windows</p>

<p><img class="figure" alt="Figure 9-18" src="http://html5hacks.com/images/chapter9-images/9-18.png"></p>

<p>Looking good.</p>

<p>But before we get started, lets set up our EventSource.</p>

<h2>EventSource</h2>

<p>Event Source is a super simple JavaScript API for opening a connection with an HTTP stream.
Because our receiver pages are just ‘dumb’ terminals that receive data, we have an ideal scenario for Server Side Events.
Earlier, when we discussed the Sinatra app, we showed exposing a route for the browser to connect to an HTTP stream. Well, this is where we connect!</p>

<figure class='code'><figcaption><span>es.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>  <span class="kd">var</span> <span class="nx">es</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">EventSource</span><span class="p">(</span><span class="s1">&#39;/connect&#39;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">es</span><span class="p">.</span><span class="nx">onmessage</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="kd">var</span> <span class="nx">msg</span> <span class="o">=</span> <span class="nx">$</span><span class="p">.</span><span class="nx">parseJSON</span><span class="p">(</span><span class="nx">event</span><span class="p">.</span><span class="nx">data</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>        <span class="c1">// … do something</span>
</span><span class='line'>  <span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now we can add a simple notification with the available data,</p>

<figure class='code'><figcaption><span>es.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>  <span class="kd">var</span> <span class="nx">es</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">EventSource</span><span class="p">(</span><span class="s1">&#39;/connect&#39;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">es</span><span class="p">.</span><span class="nx">onmessage</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="kd">var</span> <span class="nx">msg</span> <span class="o">=</span> <span class="nx">$</span><span class="p">.</span><span class="nx">parseJSON</span><span class="p">(</span><span class="nx">event</span><span class="p">.</span><span class="nx">data</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="c1">// … Notify</span>
</span><span class='line'>  <span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>And here is the final script for the admin:</p>

<figure class='code'><figcaption><span>es.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>  <span class="nx">$</span><span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">$</span><span class="p">(</span><span class="s1">&#39;#send&#39;</span><span class="p">).</span><span class="nx">click</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>      <span class="nx">event</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'>      <span class="kd">var</span> <span class="nx">notification</span> <span class="o">=</span> <span class="p">{</span><span class="nx">message</span><span class="o">:</span> <span class="nx">$</span><span class="p">(</span><span class="s1">&#39;#notification&#39;</span><span class="p">).</span><span class="nx">val</span><span class="p">()};</span>
</span><span class='line'>
</span><span class='line'>      <span class="nx">$</span><span class="p">.</span><span class="nx">post</span><span class="p">(</span> <span class="s1">&#39;/push&#39;</span><span class="p">,</span> <span class="nx">notification</span><span class="p">,</span><span class="s1">&#39;json&#39;</span><span class="p">);</span>
</span><span class='line'>    <span class="p">})</span>
</span><span class='line'>  <span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Installing jQuery.notify</h2>

<p>For our Push Notifcations we will make use of Eric Hynds great jQuery plugin jquery-notify, located here at github: [github.com/ehynds/jquery-notify] (<a href="https://github.com/ehynds/jquery-notify">https://github.com/ehynds/jquery-notify</a>)</p>

<p>In order to display the notification, we will need to include some markup to the receiver page.</p>

<figure class='code'><figcaption><span>receiver.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;div</span> <span class="na">id=</span><span class="s">&quot;container&quot;</span> <span class="na">style=</span><span class="s">&quot;display:none&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>    <span class="nt">&lt;div</span> <span class="na">id=</span><span class="s">&quot;basic-template&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>        <span class="nt">&lt;a</span> <span class="na">class=</span><span class="s">&quot;ui-notify-cross ui-notify-close&quot;</span> <span class="na">href=</span><span class="s">&quot;#&quot;</span><span class="nt">&gt;</span>x<span class="nt">&lt;/a&gt;</span>
</span><span class='line'>        <span class="nt">&lt;h1&gt;</span>#{title}<span class="nt">&lt;/h1&gt;</span>
</span><span class='line'>        <span class="nt">&lt;p&gt;</span>#{text}<span class="nt">&lt;/p&gt;</span>
</span><span class='line'>    <span class="nt">&lt;/div&gt;</span>
</span><span class='line'><span class="nt">&lt;/div&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>This creates a hidden div tag in the bottom of the document. We are not showing the CSS that uses “display: none” to hide it, but you can see more by examining the source code in the companion git repo.</p>

<p>Figure 9.19 Inspecting the DOM in Chrome Dev Tools</p>

<p><img class="figure" alt="Figure 9-19" src="http://html5hacks.com/images/chapter9-images/9-19.png"></p>

<p>In order for jQuery.notify to initialize, you must first call the following:</p>

<figure class='code'><figcaption><span>es.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nx">$</span><span class="p">(</span><span class="s2">&quot;#container&quot;</span><span class="p">).</span><span class="nx">notify</span><span class="p">({</span>
</span><span class='line'>  <span class="nx">speed</span><span class="o">:</span> <span class="mi">500</span><span class="p">,</span>
</span><span class='line'>  <span class="nx">expires</span><span class="o">:</span> <span class="kc">false</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p>And here is the final script for the receiver:</p>

<figure class='code'><figcaption><span>es.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nx">$</span><span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">$</span><span class="p">(</span><span class="s2">&quot;#container&quot;</span><span class="p">).</span><span class="nx">notify</span><span class="p">({</span>
</span><span class='line'>      <span class="nx">speed</span><span class="o">:</span> <span class="mi">500</span><span class="p">,</span>
</span><span class='line'>      <span class="nx">expires</span><span class="o">:</span> <span class="kc">false</span>
</span><span class='line'>  <span class="p">});</span>
</span><span class='line'>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">es</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">EventSource</span><span class="p">(</span><span class="s1">&#39;/connect&#39;</span><span class="p">);</span>
</span><span class='line'>  <span class="nx">es</span><span class="p">.</span><span class="nx">onmessage</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="kd">var</span> <span class="nx">msg</span> <span class="o">=</span> <span class="nx">$</span><span class="p">.</span><span class="nx">parseJSON</span><span class="p">(</span><span class="nx">event</span><span class="p">.</span><span class="nx">data</span><span class="p">);</span>
</span><span class='line'>    <span class="nx">$</span><span class="p">(</span><span class="s2">&quot;#container&quot;</span><span class="p">).</span><span class="nx">notify</span><span class="p">(</span><span class="s2">&quot;create&quot;</span><span class="p">,</span> <span class="p">{</span>
</span><span class='line'>        <span class="nx">title</span><span class="o">:</span> <span class="nx">msg</span><span class="p">.</span><span class="nx">timestamp</span><span class="p">,</span>
</span><span class='line'>        <span class="nx">text</span><span class="o">:</span> <span class="nx">msg</span><span class="p">.</span><span class="nx">notification</span>
</span><span class='line'>    <span class="p">});</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">})</span>
</span></code></pre></td></tr></table></div></figure>


<p>It’s that simple. The EventSource API is minimal and plugging it into a web framework like Sinatra or Node.js is straightforward.</p>

<p>Now, as we submit notifications from the admin page, our receiver pages are updated with time stamped notifications:</p>

<p>Figure 9.20 Pushing Notifications to the Connected Browsers</p>

<p><img class="figure" alt="Figure 9-20" src="http://html5hacks.com/images/chapter9-images/9-20.png"></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Turn Your Web App into a Windows 8 App]]></title>
    <link href="http://html5hacks.com/blog/2013/04/02/make-your-web-app-to-a-windows-8-app/"/>
    <updated>2013-04-02T01:17:00-05:00</updated>
    <id>http://html5hacks.com/blog/2013/04/02/make-your-web-app-to-a-windows-8-app</id>
    <content type="html"><![CDATA[<p>I talk a lot about just how similar the Windows 8 App environment is to developing for the Web.  Since windows 8 uses the same rendering engine as IE10, and the same JavaScript engine as IE10, building a Windows 8 App with JavaScript is in fact, building a web app.  We’ll talk about some of the keys to success but first, let’s take a step by step walk through converting one of my favorite web apps into a Windows 8 App.
First thing first, you need to make sure your using <a href="http://www.microsoft.com/visualstudio/eng/products/visual-studio-express-products">Visual Studio 2012</a> (I’m using the Express version which is free).  Since Visual Studio 2012 has a requirement of Windows 8, you’ll need to be running Windows 8 as well.
We’re going to be taking the new fantastic game “YetiBowl” for our conversion.  You can play a web version of the game <a href="http://touch.azurewebsites.net/yeti/game.html">here</a>.</p>

<p><img class="figure" alt="Figure 7-1" src="http://html5hacks.com/images/win8app/ieweb.png"></p>

<p>Once your done playing go to codeplex and download the project:</p>

<p><a href="http://yetibowl.codeplex.com">http://yetibowl.codeplex.com</a></p>

<p>If you open up the content in the directory marked “web”  you’ll see all the code for the YetiBowl game.  Now let’s go to Visual Studio and open up a new &ldquo;Blank&rdquo; JavaScript App:</p>

<p><img class="figure" alt="Figure 7-1" src="http://html5hacks.com/images/win8app/VS1.PNG"></p>

<p>Next, go back to your recently downloaded code, and copy all the content from the &ldquo;web&rdquo; folder</p>

<p><img class="figure" alt="Figure 7-1" src="http://html5hacks.com/images/win8app/VS2.png"></p>

<p>Now go back to your new Visual Studio project, and find the solutions explorer on the right side of the screen, past your code into your project:</p>

<p><img class="figure" alt="Figure 7-1" src="http://html5hacks.com/images/win8app/VS3.png"></p>

<p>Before our code is going to work, we need to open up our package.appxmanifest and make one small change.  Find the field for &ldquo;start page&rdquo; and change it to the name of your html file(game.html):</p>

<p><img class="figure" alt="Figure 7-1" src="http://html5hacks.com/images/win8app/VS4.PNG"></p>

<p>Now, hit F5 and see what happens!  That’s all it takes, our YetiBowl game is now a Windows 8 Store App, and a pretty fine one at that.  Our web app code just works in Windows 8.</p>

<p><img class="figure" alt="Figure 7-1" src="http://html5hacks.com/images/win8app/VS5.PNG"></p>

<h2>Add a Little Delight for your users</h2>

<p>Now that you have your app up and running, let’s use one of the favorite Windows 8 API to add some additional features to our app.  With a few lines of code we’ll be able to add the ability to “share” with the Windows 8 Share Charm.
  To keep it easy, let’s go to the bottom of our game.html file and add a script tag.  We’ll then past a few lines of code into it:</p>

<figure class='code'><figcaption><span>win8.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>
</span><span class='line'>
</span><span class='line'>
</span><span class='line'>
</span><span class='line'>        <span class="kd">var</span> <span class="nx">dataTransferManager</span> <span class="o">=</span> <span class="nx">Windows</span><span class="p">.</span><span class="nx">ApplicationModel</span><span class="p">.</span><span class="nx">DataTransfer</span><span class="p">.</span><span class="nx">DataTransferManager</span><span class="p">.</span><span class="nx">getForCurrentView</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'>
</span><span class='line'>
</span><span class='line'>        <span class="nx">dataTransferManager</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s2">&quot;datarequested&quot;</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>            <span class="c1">// Code to handle event goes here.</span>
</span><span class='line'>
</span><span class='line'>
</span><span class='line'>            <span class="kd">var</span> <span class="nx">request</span> <span class="o">=</span> <span class="nx">e</span><span class="p">.</span><span class="nx">request</span><span class="p">;</span>
</span><span class='line'>            <span class="nx">request</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">properties</span><span class="p">.</span><span class="nx">title</span> <span class="o">=</span> <span class="s2">&quot;I&#39;m Rocking out with the Yeti&quot;</span><span class="p">;</span>
</span><span class='line'>            <span class="nx">request</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">properties</span><span class="p">.</span><span class="nx">description</span> <span class="o">=</span> <span class="s2">&quot;HTML share from YetiBowl Game&quot;</span><span class="p">;</span>
</span><span class='line'>            <span class="kd">var</span> <span class="nx">localImage</span> <span class="o">=</span> <span class="s1">&#39;ms-appx:///media/logos/yeti_logo.png&#39;</span><span class="p">;</span>
</span><span class='line'>            <span class="kd">var</span> <span class="nx">htmlExample</span> <span class="o">=</span> <span class="s2">&quot;&lt;p&gt;Here&#39;s to some fun with the Yeti. If your not playing YetiBowl, then your not really having fun!&lt;/p&gt;&lt;div&gt;&lt;img src=\&quot;&quot;</span> <span class="o">+</span> <span class="nx">localImage</span> <span class="o">+</span> <span class="s2">&quot;\&quot;&gt;.&lt;/div&gt;&quot;</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>            <span class="kd">var</span> <span class="nx">htmlFormat</span> <span class="o">=</span> <span class="nx">Windows</span><span class="p">.</span><span class="nx">ApplicationModel</span><span class="p">.</span><span class="nx">DataTransfer</span><span class="p">.</span><span class="nx">HtmlFormatHelper</span><span class="p">.</span><span class="nx">createHtmlFormat</span><span class="p">(</span><span class="nx">htmlExample</span><span class="p">);</span>
</span><span class='line'>            <span class="nx">request</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">setHtmlFormat</span><span class="p">(</span><span class="nx">htmlFormat</span><span class="p">);</span>
</span><span class='line'>            <span class="kd">var</span> <span class="nx">streamRef</span> <span class="o">=</span> <span class="nx">Windows</span><span class="p">.</span><span class="nx">Storage</span><span class="p">.</span><span class="nx">Streams</span><span class="p">.</span><span class="nx">RandomAccessStreamReference</span><span class="p">.</span><span class="nx">createFromUri</span><span class="p">(</span><span class="k">new</span> <span class="nx">Windows</span><span class="p">.</span><span class="nx">Foundation</span><span class="p">.</span><span class="nx">Uri</span><span class="p">(</span><span class="nx">localImage</span><span class="p">));</span>
</span><span class='line'>            <span class="nx">request</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">resourceMap</span><span class="p">[</span><span class="nx">localImage</span><span class="p">]</span> <span class="o">=</span> <span class="nx">streamRef</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>        <span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p><img class="figure" alt="Figure 7-1" src="http://html5hacks.com/images/win8app/VS6.PNG"></p>

<p>You can find out more about the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh758314.aspx">share charm here</a>, but we are basically taking advantage of one of the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br211377.aspx">many Windows RT APIs</a> that you have access to via JavaScript inside your Windows 8 App.  Once you’ve added this above code, you’ll now be able to share info from your Yeti Bowl Game to other apps you have installed.</p>

<p><img class="figure" alt="Figure 7-1" src="http://html5hacks.com/images/win8app/VS7.PNG"></p>

<p><img class="figure" alt="Figure 7-1" src="http://html5hacks.com/images/win8app/VS8.PNG"></p>

<h2>A Few Closing Notes</h2>

<p>It is very easy to move your web apps to Windows 8 where you have access to a whole series of new APIs and functionality that isn’t safe to expose on the web.  That being the case, it’s important that you look into the <a href="http://msdn.microsoft.com/en-us/library/windows/apps/hh849625.aspx">security model</a> that is implemented in Windows 8 Apps.  Using a JavaScript library?  Many libraries like <a href="http://www.yuiblog.com/blog/2013/03/12/windows-8-loves-yui/">YUI</a> and <a href="http://blogs.msdn.com/b/interoperability/archive/2013/03/29/jquery-adds-support-for-windows-store-apps-creates-new-opportunities-for-javascript-open-source-developers.aspx">jQuery</a> already work within the Windows 8 App environment.
It’s that easy, reuse your code, and your skills to build Windows 8 Store Apps.</p>

<p>Author: Jeff Burtoft &ndash; <a href="http://www.twitter.com/boyofgreen">@boyofgreen</a>
code sample: <a href="http://touch.azurewebsites.net/yeti/game.html">http://touch.azurewebsites.net/yeti/game.html</a></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Win a free copy of HTML5 Hacks]]></title>
    <link href="http://html5hacks.com/blog/2013/03/26/oreilly-webcast-rethinking-the-possibilities-of-browser-based-apps-with-html5/"/>
    <updated>2013-03-26T19:52:00-05:00</updated>
    <id>http://html5hacks.com/blog/2013/03/26/oreilly-webcast-rethinking-the-possibilities-of-browser-based-apps-with-html5</id>
    <content type="html"><![CDATA[<p>Sign up on our mailing list and be put into a draw to win a free ebook:</p>

<!-- Begin MailChimp Signup Form -->


<p><link href="http://cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css"></p>

<div id="mc_embed_signup">
<form action="http://jessecravens.us2.list-manage1.com/subscribe/post?u=e00a501b9d5ba6aa43acd55a7&amp;id=95bec8136d" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
  <input type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
  <div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
</form>
</div>


<!--End mc_embed_signup-->


<h2>O&#8217;Reilly Webcast: Rethinking the Possibilities of Browser-based Apps with HTML5</h2>

<p>Wednesday, March 27, 2013
10AM PT, San Francisco | 5pm &ndash; London | 1pm &ndash; New York | Thu, Mar 28th at 4am &ndash; Sydney | Thu, Mar 28th at 2am &ndash; Tokyo | Thu, Mar 28th at 1am &ndash; Beijing | 10:30pm &ndash; Mumbai</p>

<p>Here is a link to the archived presentation:
<a href="http://event.on24.com/eventRegistration/EventLobbyServlet?target=lobby.jsp&amp;eventid=561480&amp;sessionid=1&amp;key=76D1FED238FE290C4AC3A7CDDB4E23E5&amp;eventuserid=78868897">Watch the webcast in its original format</a></p>

<p>Presented by: Jeff Burtoft, Jesse Cravens</p>

<p>Duration: Approximately 60 minutes.</p>

<p>From canvas to web workers and file transfer to blob management, join us for a hands-on webcast to see HTML5 demos and code samples that will have you rethinking the possibilities of browser based apps. Watch the competitiveness mount, as these two innovative Hackers try to one-up each other through demonstrations of each of their most inspired hacks.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[SXSWi 2013: 'Battle of the HTML5 Hackers' and 'HTML5 Hacks' Book Signing]]></title>
    <link href="http://html5hacks.com/blog/2013/03/12/sxswi-2013-battle-of-the-html5-hackers/"/>
    <updated>2013-03-12T23:55:00-05:00</updated>
    <id>http://html5hacks.com/blog/2013/03/12/sxswi-2013-battle-of-the-html5-hackers</id>
    <content type="html"><![CDATA[<p>We had a great turnout for the &lsquo;Battle of the HTML5 Hackers&rsquo; presentation at SXSWi on Tuesday.</p>

<p><img class="imgL300" alt="SXSWi 2013: Battle of the HTML5 Hackers - Jesse Cravens and Jeff Burtoft" src="http://html5hacks.com/images/sxsw13/sxsw13-crowd.jpg"></p>

<p>Using our best CDD (Conference Driven Devlopment) techniques, we walked the audience through the creation of <a href="http://nerdclustr.jit.su">Nerdclustr</a>: an HTML5 mobile Application that helps nerds find other like-minded nerds at conferences events.</p>

<p>Using realtime and mapping technolgies, the app visualizes nerd behavior in map pin clusters.</p>

<p><img class="imgR200" alt="Nerdclustr: SXSWi 2013 Ballroom G Austin Convention Center"  src="http://html5hacks.com/images/sxsw13/sxsw13-app.png"></p>

<p>Here is a shot of the app in action (Ballroom G in the Austin Convention Center); it performed well during the presentation. Thanks to <a href="https://www.nodejitsu.com/">Nodjitsu</a> for the quality node.js WebSocket service. After a 2-day hackathon to get the app launched, I ran through a number of deployment options, many of which I have used before for Rails applications. <a href="https://www.nodejitsu.com/">Nodjitsu</a> won out in that it actually supported the WebSokcet protocol and made deployment super simple using the jitsu CLI.</p>

<p><img class="imgL200" alt="Jesse Cravens and Jeff Burtoft: SXSWi 2013 - HTML5 Hacks Book Signing"  src="http://html5hacks.com/images/sxsw13/sxsw13-booksigning.png"></p>

<p>Nerdclustr source code is available <a href="https://github.com/html5hacks/nerd-clustr">here</a>.</p>

<p>During the book signing, the bookstore informed us there were only 3 copies left. I&rsquo;m not keen to the selection process of books, but I was little surprised at the limited number of technical books. This is certainly a reflection of the SXSWi demographic, and we also tailored our content and presentation style to this audience.</p>

<p>The slide deck is available here:</p>

<script async class="speakerdeck-embed" data-id="c69c92f06d880130bfaa22000a1f8363" data-ratio="1.77777777777778" src="http://html5hacks.com//speakerdeck.com/assets/embed.js"></script>




<hr>


<p>Stay tuned for our next presentation happening online, through O&#8217;Reilly Webcasts. Join us for <a href="http://www.oreillynet.com/pub/e/2566">&lsquo;Rethinking the Possibilities of Browser-based Apps with HTML5&rsquo;</a> on Wednesday, March 27, 2013 10AM PT.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Build a Windows 8 App with YUI]]></title>
    <link href="http://html5hacks.com/blog/2013/03/10/build-a-windows-8-app-with-yui/"/>
    <updated>2013-03-10T19:10:00-05:00</updated>
    <id>http://html5hacks.com/blog/2013/03/10/build-a-windows-8-app-with-yui</id>
    <content type="html"><![CDATA[<p>I’ve always been a big fan of YUI.  YUI has taught me how to write good, scalable code.  If I ever wanted to know the “right” way to do something, I looked back at how the YUI devs did it, and I would do it the same way.  In the last few years, with the release of YUI3, that standard is even higher.  The encapsulation practices and the decentralization of the code base has made it pleasure to develop, and a rock solid foundation for my applications.</p>

<p>You can imagine how excited I was to introduce this honored, experienced titan to the new kid on the block, WinJS.  For those of you who don’t know, WinJS is the library that runs exclusively inside of Windows 8 Apps written in JavaScript and HTML5.  For those of you who aren’t familiar with the concept, Microsoft has written this kick-ass ecosystem for Windows 8 in which we as developers can build Windows Store Apps with web technologies (js/css/html) just as we would with any managed code base like c++ or c#.  WinJS provides you with core functionality like templating, file system access, reusable UI components, and service calls via XHR.  Widows 8 Apps use the same rendering engine and the same JavaScript engine as IE10, and being a sandboxed app, you also have access to a whole slew of APIs from the WinRT service layer.  You can read all about how this works <a href="http://msdn.microsoft.com/en-us/library/windows/apps/br211377.aspx">directly from MSDN</a>.</p>

<p>Since your Windows 8 Apps are running IE10 components you can pull in your favorite JavaScript library to provide you with app functionality.  In my case, my favorite library has always been YUI, so my goal was to shoehorn YUI into the Windows 8 App.  Much to my surprise, I never once had to pull out the shoehorn, YUI not only worked well inside the app, but it also worked seamlessly with WinJS.  This is my story. A love story really, of how Windows 8 Loves YUI.</p>

<h2>What you need</h2>

<p>If you’re a YUI developer, you probably know how this all works.  If you want to, and are able to, use the Yahoo CDN, then there is very little barrier to entry; in fact it’s incredibly simple.   You basically have two simple steps.</p>

<p>Step 1:  add the YUI seed to your page:</p>

<figure class='code'><figcaption><span>win8.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>
</span><span class='line'>
</span><span class='line'><span class="c1">// Put the YUI seed file on your page.</span>
</span><span class='line'><span class="o">&lt;</span><span class="nx">script</span> <span class="nx">src</span><span class="o">=</span><span class="s2">&quot;http://yui.yahooapis.com/3.8.1/build/yui/yui-min.js&quot;</span><span class="o">&gt;&lt;</span><span class="err">/script&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Step 2: start a new instance:</p>

<figure class='code'><figcaption><span>win8.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>
</span><span class='line'><span class="o">&lt;</span><span class="nx">script</span><span class="o">&gt;</span>
</span><span class='line'><span class="c1">// Create a YUI sandbox on your page.</span>
</span><span class='line'><span class="nx">YUI</span><span class="p">().</span><span class="nx">use</span><span class="p">(</span><span class="s1">&#39;node&#39;</span><span class="p">,</span> <span class="s1">&#39;event&#39;</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">Y</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="c1">// The Node and Event modules are loaded and ready to use.</span>
</span><span class='line'>    <span class="c1">// Your code goes here!</span>
</span><span class='line'><span class="p">});</span>
</span><span class='line'><span class="o">&lt;</span><span class="err">/script&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Pretty Simple.  Now for our example. We’ll be running code in the local context of our app, so for security reasons, we can’t load our JS libraries from a CDN- they have to be packaged with the app which we’ll discuss more in a bit.  So in our case, you’ll also need another tool provided by the YUI team, the <a href="http://yuilibrary.com/yui/configurator/">YUI configurator</a>.   The configurator will be used to determine what JS files we want to add to each of our pages.  Also, you’re going to need a local copy of the library as well, so download that <a href="https://github.com/yui">from github</a>.
To build our pages into a Windows 8 App, you’ll need a copy of visual Studio 2012. My suggestion is to go download yourself a copy of <a href="http://www.microsoft.com/visualstudio/eng/products/visual-studio-express-for-windows-8">Visual Studio Express for Windows 8</a>.  This version of VS is free, but it has everything you need to build a Windows 8 App.  It’s more than your average free editor as well.  It has incredible code completion and intelisence.  Visual Studio express 2012 has Windows 8 as a system requirement, so by default you need to be running on a Windows 8 machine (or VM) as well.</p>

<h2>Let’s take it up a Notch</h2>

<p>I want to hit home the idea that YUI just works inside of a Windows 8 App, so were’ going to take a few samples straight from the YUI library and build them into an app.  We’ll basically be creating a three page app consisting of a home page and two examples pages.  We’re going to Use WinJS for high level things like Navigation, App Status, and cool Windows 8 features, and use YUI for all the functionality of our App.
 Let’s kick it off by opening a brand new project in Visual Studio.  Let’s start by opening a new “navigation” app.</p>

<p>  <img class="figure" alt="Figure 7-1" src="http://html5hacks.com/images/chapter-jeff/vs-menu.png"></p>

<p>You’ll find the navigation boiler plate app to be quite interesting.  Out of the box, WinJS turns this code into a single page application.  If you were to run this code, you would see a blank page that has the text on it “content goes here.” But if you look into your code a bit, you’ll see that this text doesn’t actually appear in our default.html page (this is our starting page).  Instead, it appears in the file called home.html (which is located in a \pages\home\home.html).  This is the magic that is the navigation app.  When we use WinJS for navigation, we don’t need to worry about state or page loads, it’s all taken care of for us.
  In this case, our default.html file contains our template target:</p>

<figure class='code'><figcaption><span>win8.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'>
</span><span class='line'><span class="nt">&lt;div</span> <span class="na">id=</span><span class="s">&quot;contenthost&quot;</span> <span class="na">data-win-control=</span><span class="s">&quot;Application.PageControlNavigator&quot;</span> <span class="na">data-win-options=</span><span class="s">&quot;{home: &#39;/pages/home/home.html&#39;}&quot;</span><span class="nt">&gt;&lt;/div&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>In a WinJS Navigation App, each html file has an associated .js file and .css file.  If we open up default.js we see this code attached to our process all method in a “promise”:</p>

<figure class='code'><figcaption><span>win8.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>
</span><span class='line'><span class="nx">WinJS</span><span class="p">.</span><span class="nx">UI</span><span class="p">.</span><span class="nx">processAll</span><span class="p">().</span><span class="nx">then</span><span class="p">(</span><span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
</span><span class='line'>                <span class="k">if</span> <span class="p">(</span><span class="nx">nav</span><span class="p">.</span><span class="nx">location</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>                    <span class="nx">nav</span><span class="p">.</span><span class="nx">history</span><span class="p">.</span><span class="nx">current</span><span class="p">.</span><span class="nx">initialPlaceholder</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span>
</span><span class='line'>                    <span class="k">return</span> <span class="nx">nav</span><span class="p">.</span><span class="nx">navigate</span><span class="p">(</span><span class="nx">nav</span><span class="p">.</span><span class="nx">location</span><span class="p">,</span> <span class="nx">nav</span><span class="p">.</span><span class="nx">state</span><span class="p">);</span>
</span><span class='line'>                <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
</span><span class='line'>                    <span class="k">return</span> <span class="nx">nav</span><span class="p">.</span><span class="nx">navigate</span><span class="p">(</span><span class="nx">Application</span><span class="p">.</span><span class="nx">navigator</span><span class="p">.</span><span class="nx">home</span><span class="p">);</span>
</span><span class='line'>                <span class="p">}</span>
</span><span class='line'>            <span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p>The &ldquo;process all&rdquo; method parses the page and processes any page construction that is necessary before rendering the page.  Once that is complete the “.then()” promise fires off the navigation.  Without getting into too much detail, there is a library component added to this style of app called navigator.js, which adds this functionally for us.
The file “home.html” will be our navigation point in this app, but we want to create some new pages to navigate to.  Let’s go ahead and add our first one.  To keep our code clean, the first thing I want to do is add a directory inside our “\pages\” directory called “duck”.  I’ll use this directory to keep my new page separate from my other pages.  Now let’s go into Visual Studio, and right click on that new folder.  In our contextual menu, we’ll have the option to add a “new item.”</p>

<p><img class="figure" alt="Figure 7-1" src="http://html5hacks.com/images/chapter-jeff/vs-menu2.png"></p>

<p>Add a new “page control” which we will call duck.html.  Once we hit add, not only is an HTML file created, but an associated .js and .css file as well.</p>

<p><img class="figure" alt="Figure 7-1" src="http://html5hacks.com/images/chapter-jeff/vs-page.png"></p>

<p>This is the new page we are going to navigate to.  If you open up duck.js, you’ll see we have some content already created for us:</p>

<figure class='code'><figcaption><span>win8.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>
</span><span class='line'>
</span><span class='line'><span class="c1">// For an introduction to the Page Control template, see the following documentation:</span>
</span><span class='line'><span class="c1">// http://go.microsoft.com/fwlink/?LinkId=232511</span>
</span><span class='line'><span class="p">(</span><span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
</span><span class='line'>    <span class="s2">&quot;use strict&quot;</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>    <span class="nx">WinJS</span><span class="p">.</span><span class="nx">UI</span><span class="p">.</span><span class="nx">Pages</span><span class="p">.</span><span class="nx">define</span><span class="p">(</span><span class="s2">&quot;/pages/duck/duck.html&quot;</span><span class="p">,</span> <span class="p">{</span>
</span><span class='line'>        <span class="c1">// This function is called whenever a user navigates to this page. It</span>
</span><span class='line'>        <span class="c1">// populates the page elements with the app&#39;s data.</span>
</span><span class='line'>        <span class="nx">ready</span><span class="o">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">element</span><span class="p">,</span> <span class="nx">options</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>            <span class="c1">// TODO: Initialize the page here.</span>
</span><span class='line'>        <span class="p">},</span>
</span><span class='line'>
</span><span class='line'>        <span class="nx">unload</span><span class="o">:</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
</span><span class='line'>            <span class="c1">// TODO: Respond to navigations away from this page.</span>
</span><span class='line'>        <span class="p">},</span>
</span><span class='line'>
</span><span class='line'>        <span class="nx">updateLayout</span><span class="o">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">element</span><span class="p">,</span> <span class="nx">viewState</span><span class="p">,</span> <span class="nx">lastViewState</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>            <span class="c1">/// &lt;param name=&quot;element&quot; domElement=&quot;true&quot; /&gt;</span>
</span><span class='line'>
</span><span class='line'>            <span class="c1">// TODO: Respond to changes in viewState.</span>
</span><span class='line'>        <span class="p">}</span>
</span><span class='line'>    <span class="p">});</span>
</span><span class='line'><span class="p">})();</span>
</span></code></pre></td></tr></table></div></figure>


<p>You’ll notice the first thing in our blind function is that we have our page “defined”.  This code will be called whenever a user navigates to this page, so in our case, we’ll want to use this method to wrap all of our JavaScript from our YUI examples.
Now it’s time to go get a few cool examples.  Let’s start with a little game that takes me back to my days of being raised by “carnies” (that’s carnival folk for all those who aren’t from Texas).</p>

<p>  <img class="figure" alt="Figure 7-1" src="http://html5hacks.com/images/chapter-jeff/library-page.png"></p>

<p>This <a href="http://yuilibrary.com/yui/docs/node/ducks.html">duck shooter game</a> demonstrates the use of the Node list.  I basically want to pull this sample right off the library and dump into a Windows 8 App. On this page scroll down to the full code example.  Copy the CSS into the duck.css file, merge the HTML into your duck.html file (be sure not to delete the references to the already existing .js and .css files) and then take the YUI use() statement and copy it into the “ready” method inside of the duck.js file</p>

<figure class='code'><figcaption><span>win8.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>
</span><span class='line'>        <span class="nx">ready</span><span class="o">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">element</span><span class="p">,</span> <span class="nx">options</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>            <span class="c1">// Paste Your Code right here!</span>
</span><span class='line'>        <span class="p">},</span>
</span></code></pre></td></tr></table></div></figure>


<h2>A Match Made in Heaven</h2>

<p>Next is the step where YUI and WinJS actually meet.  For me, this is like the “as you wish” moment from the Princess Bride where Princess Buttercup realized she truly loved Westley too.  It’s going to work so seamlessly.    At this point there is one BIG thing missing.  YUI.  We need to load YUI into our local context so we can reference it from our local pages.  First things first, you need to go to github and download a copy of the library.  Now in “file explorer window” select the “build” directory from the library, copy it and then head back to your solutions explorer and paste it into your app.  Okay, that wasn’t hard at all, but there is one more thing to plan for.  When you use the YUI CDN along with the loader, you get a magical file concoction that loads all the proper files for you based on your YUI requires statement.  Since we aren’t using the CDN, we don’t get that magic.  The good news is, YUI’s got an app for that.  It’s called the YUI configurator and it’s pretty snazzy too.  Let’s quickly review our use statement in our sample, and you will see that are using two library components:</p>

<figure class='code'><figcaption><span>win8.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>
</span><span class='line'><span class="nx">YUI</span><span class="p">().</span><span class="nx">use</span><span class="p">(</span><span class="s1">&#39;transition&#39;</span><span class="p">,</span> <span class="s1">&#39;button&#39;</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">Y</span><span class="p">)</span> <span class="p">{</span><span class="err">…</span>
</span></code></pre></td></tr></table></div></figure>


<p>So let’s go over to the configurator and select those two components from the list of required components.  There are a few other settings we can update to make our life easier.  First, make sure you have the box unchecked to load separate files, not combined files.  Next, you can update your root path; in this case we will update it to “/js/build” since that is where the files will be in our app.  Once you have these settings in place, you should have a nice list of files that we need to load into our DOM in order to have our demo function:</p>

<figure class='code'><figcaption><span>win8.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
<span class='line-number'>36</span>
<span class='line-number'>37</span>
<span class='line-number'>38</span>
<span class='line-number'>39</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/yui-base/yui-base.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/oop/oop.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/attribute-core/attribute-core.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/classnamemanager/classnamemanager.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/event-custom-base/event-custom-base.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/features/features.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/dom-core/dom-core.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/dom-base/dom-base.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/selector-native/selector-native.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/selector/selector.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/node-core/node-core.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/node-base/node-base.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/event-base/event-base.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/button-core/button-core.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/event-custom-complex/event-custom-complex.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/attribute-observable/attribute-observable.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/attribute-extras/attribute-extras.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/attribute-base/attribute-base.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/attribute-complex/attribute-complex.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/base-core/base-core.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/base-observable/base-observable.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/base-base/base-base.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/pluginhost-base/pluginhost-base.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/pluginhost-config/pluginhost-config.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/base-pluginhost/base-pluginhost.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/event-synthetic/event-synthetic.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/event-focus/event-focus.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/dom-style/dom-style.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/node-style/node-style.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/widget-base/widget-base.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/widget-base-ie/widget-base-ie.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/widget-htmlparser/widget-htmlparser.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/widget-skin/widget-skin.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/event-delegate/event-delegate.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/node-event-delegate/node-event-delegate.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/widget-uievents/widget-uievents.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/button/button.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'><span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/transition/transition.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Paste that into the header, and we are ready to go.  What’s going to happen next is that when we navigate to duck.html, WinJS will fire the “ready” method and execute the YUI.use() statement from the demo page.  We still have one small problem- we don’t yet have any way to navigate to this code.  Never fear, we can fix that. To navigate to a page, you really just need to fire one method:</p>

<figure class='code'><figcaption><span>win8.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>
</span><span class='line'>
</span><span class='line'><span class="nx">WinJS</span><span class="p">.</span><span class="nx">Navigation</span><span class="p">.</span><span class="nx">navigate</span><span class="p">(</span><span class="s2">&quot;PathToFile&quot;</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>When this method is fired, your app will then navigate to the page referenced by the string passed into it.  Remember, our WinJS apps are all single page applications, so there is no page load- instead your new page content is loaded inside of your app container.  In this case, the container was defined inside the default.html file.  In addition to the HTML being injected into your DOM from your new page, it’s references are added to ( .js files or .css files).  It’s quite a smooth process.
To make the whole thing a bit easier on me, I’m going to crack open my home.js file, and have a bit of code loaded up that will make my navigation even more familiar.  Remember, when the “home.html” file is loaded, our “home.js” file is executed as well.  Inside the “ready” method of this file, we’re going to add a few lines of code so the file appears as below:</p>

<figure class='code'><figcaption><span>win8.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>
</span><span class='line'>
</span><span class='line'><span class="p">(</span><span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
</span><span class='line'>    <span class="s2">&quot;use strict&quot;</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>    <span class="nx">WinJS</span><span class="p">.</span><span class="nx">UI</span><span class="p">.</span><span class="nx">Pages</span><span class="p">.</span><span class="nx">define</span><span class="p">(</span><span class="s2">&quot;/pages/home/home.html&quot;</span><span class="p">,</span> <span class="p">{</span>
</span><span class='line'>        <span class="c1">// This function is called whenever a user navigates to this page. It</span>
</span><span class='line'>        <span class="c1">// populates the page elements with the app&#39;s data.</span>
</span><span class='line'>        <span class="nx">ready</span><span class="o">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">element</span><span class="p">,</span> <span class="nx">options</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>
</span><span class='line'>
</span><span class='line'>            <span class="nx">WinJS</span><span class="p">.</span><span class="nx">Utilities</span><span class="p">.</span><span class="nx">query</span><span class="p">(</span><span class="s2">&quot;a&quot;</span><span class="p">).</span><span class="nx">listen</span><span class="p">(</span><span class="s2">&quot;MSPointerDown&quot;</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">evt</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>                <span class="c1">// dont load this link in the main window</span>
</span><span class='line'>                <span class="nx">evt</span><span class="p">.</span><span class="nx">preventDefault</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'>                <span class="c1">// get target element</span>
</span><span class='line'>                <span class="kd">var</span> <span class="nx">link</span> <span class="o">=</span> <span class="nx">evt</span><span class="p">.</span><span class="nx">target</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'>                <span class="c1">//call navigate and pass the href of the link</span>
</span><span class='line'>                <span class="nx">WinJS</span><span class="p">.</span><span class="nx">Navigation</span><span class="p">.</span><span class="nx">navigate</span><span class="p">(</span><span class="nx">link</span><span class="p">.</span><span class="nx">href</span><span class="p">);</span>
</span><span class='line'>            <span class="p">});</span>
</span><span class='line'>
</span><span class='line'>        <span class="p">}</span>
</span><span class='line'>    <span class="p">});</span>
</span><span class='line'><span class="p">})();</span>
</span></code></pre></td></tr></table></div></figure>


<p>You’ll notice I added a listener to all of my anchor tags that prevents the default behavior and then takes the url from the href, and passes it into our navigation method.  With the addition of this code, I can now simply add anchor tags into my code as I would with the web, and the navigation module will take over and provide me with page construction and high level app navigation (state for back button).
Now I can go back to my “home.html” file and add a link in to my duck app:</p>

<figure class='code'><figcaption><span>win8.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'>
</span><span class='line'>
</span><span class='line'>  <span class="nt">&lt;p&gt;&lt;a</span> <span class="na">class=</span><span class="s">&quot;duck&quot;</span> <span class="na">href=</span><span class="s">&quot;/pages/duck/duck.html&quot;</span> <span class="nt">&gt;</span>duck<span class="nt">&lt;/a&gt;&lt;/p&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Our app now navigates from the start page to the duck sample, and back again.</p>

<p><img class="figure" alt="Figure 7-1" src="http://html5hacks.com/images/chapter-jeff/screen-1.png"></p>

<p><img class="figure" alt="Figure 7-1" src="http://html5hacks.com/images/chapter-jeff/screen-2.png"></p>

<h2>Growing the App</h2>

<p>Let’s keep going with this navigation app and add a new page.  Go to your solution explorer, create a new directory inside the “pages” directory and call it &ldquo;dial&rdquo;.  Inside of it, right click and add a new page control called “dial.html”.  Again, watch the magic happen as it generates your .html file, your .js file and your .css file.
Next, navigate to the super cool <a href="http://yuilibrary.com/yui/docs/dial/dial-interactive.html">YUI sample dial app</a>:</p>

<p>  <img class="figure" alt="Figure 7-1" src="http://html5hacks.com/images/chapter-jeff/cap-3.png"></p>

<p>Here, we’re going to again copy out sample code directly from the web and move it into our app.   You have your three file types (.html, .js, .css), so use them.  Move your css from the sample style tag to your CSS file, move your HTML from the body of your sample into the body of your HTML file, and move the JS code from the sample page into the “ready” method of dial.js file. At this point, you’ll want to go back to your YUI configurator to determine what JS files you need to lean in the head of the page as well.  Your resulting HTML file should look like this:</p>

<figure class='code'><figcaption><span>win8.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
<span class='line-number'>36</span>
<span class='line-number'>37</span>
<span class='line-number'>38</span>
<span class='line-number'>39</span>
<span class='line-number'>40</span>
<span class='line-number'>41</span>
<span class='line-number'>42</span>
<span class='line-number'>43</span>
<span class='line-number'>44</span>
<span class='line-number'>45</span>
<span class='line-number'>46</span>
<span class='line-number'>47</span>
<span class='line-number'>48</span>
<span class='line-number'>49</span>
<span class='line-number'>50</span>
<span class='line-number'>51</span>
<span class='line-number'>52</span>
<span class='line-number'>53</span>
<span class='line-number'>54</span>
<span class='line-number'>55</span>
<span class='line-number'>56</span>
<span class='line-number'>57</span>
<span class='line-number'>58</span>
<span class='line-number'>59</span>
<span class='line-number'>60</span>
<span class='line-number'>61</span>
<span class='line-number'>62</span>
<span class='line-number'>63</span>
<span class='line-number'>64</span>
<span class='line-number'>65</span>
<span class='line-number'>66</span>
<span class='line-number'>67</span>
<span class='line-number'>68</span>
<span class='line-number'>69</span>
<span class='line-number'>70</span>
<span class='line-number'>71</span>
<span class='line-number'>72</span>
<span class='line-number'>73</span>
<span class='line-number'>74</span>
<span class='line-number'>75</span>
<span class='line-number'>76</span>
<span class='line-number'>77</span>
<span class='line-number'>78</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'>
</span><span class='line'>
</span><span class='line'><span class="cp">&lt;!DOCTYPE HTML&gt;</span>
</span><span class='line'><span class="nt">&lt;html&gt;</span>
</span><span class='line'>        <span class="c">&lt;!-- WinJS references --&gt;</span>
</span><span class='line'>    <span class="nt">&lt;link</span> <span class="na">href=</span><span class="s">&quot;//Microsoft.WinJS.1.0/css/ui-light.css&quot;</span> <span class="na">rel=</span><span class="s">&quot;stylesheet&quot;</span> <span class="nt">/&gt;</span>
</span><span class='line'>    <span class="nt">&lt;script </span><span class="na">src=</span><span class="s">&quot;//Microsoft.WinJS.1.0/js/base.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'>    <span class="nt">&lt;script </span><span class="na">src=</span><span class="s">&quot;//Microsoft.WinJS.1.0/js/ui.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'>    <span class="c">&lt;!-- CSS --&gt;</span>
</span><span class='line'>    <span class="nt">&lt;link</span> <span class="na">rel=</span><span class="s">&quot;stylesheet&quot;</span> <span class="na">type=</span><span class="s">&quot;text/css&quot;</span> <span class="na">href=</span><span class="s">&quot;/js/build/widget-base/assets/skins/sam/widget-base.css&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>    <span class="nt">&lt;link</span> <span class="na">rel=</span><span class="s">&quot;stylesheet&quot;</span> <span class="na">type=</span><span class="s">&quot;text/css&quot;</span> <span class="na">href=</span><span class="s">&quot;/js/build/dial/assets/skins/sam/dial.css&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>    <span class="nt">&lt;link</span> <span class="na">href=</span><span class="s">&quot;dial.css&quot;</span> <span class="na">rel=</span><span class="s">&quot;stylesheet&quot;</span> <span class="nt">/&gt;</span>
</span><span class='line'>
</span><span class='line'>    <span class="c">&lt;!-- JS --&gt;</span>
</span><span class='line'>    <span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/yui-base/yui-base-min.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'>    <span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/intl-base/intl-base-min.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'>    <span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/oop/oop-min.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'>    <span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/event-custom-base/event-custom-base-min.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'>    <span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/event-custom-complex/event-custom-complex-min.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'>    <span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/intl/intl-min.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'>    <span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/dial/lang/dial.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'>    <span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/attribute-core/attribute-core-min.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'>    <span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/attribute-observable/attribute-observable-min.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'>    <span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/attribute-extras/attribute-extras-min.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'>    <span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/attribute-base/attribute-base-min.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'>    <span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/attribute-complex/attribute-complex-min.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'>    <span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/base-core/base-core-min.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'>    <span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/base-observable/base-observable-min.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'>    <span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/base-base/base-base-min.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'>    <span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/pluginhost-base/pluginhost-base-min.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'>    <span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/pluginhost-config/pluginhost-config-min.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'>    <span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/base-pluginhost/base-pluginhost-min.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'>    <span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/classnamemanager/classnamemanager-min.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'>    <span class="nt">&lt;script </span><span class="na">type=</span><span class="s">&quot;text/javascript&quot;</span> <span class="na">src=</span><span class="s">&quot;/js/build/features/features-min.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'>
</span><span class='line'>    <span class="nt">&lt;script </span><span class="na">src=</span><span class="s">&quot;dial.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'>
</span><span class='line'>
</span><span class='line'>
</span><span class='line'><span class="nt">&lt;body</span> <span class="na">class=</span><span class="s">&quot;yui3-skin-sam&quot;</span><span class="nt">&gt;</span> <span class="c">&lt;!-- You need this skin class --&gt;</span>
</span><span class='line'>
</span><span class='line'>       <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;dial fragment&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>        <span class="nt">&lt;header</span> <span class="na">aria-label=</span><span class="s">&quot;Header content&quot;</span> <span class="na">role=</span><span class="s">&quot;banner&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>            <span class="nt">&lt;button</span> <span class="na">class=</span><span class="s">&quot;win-backbutton&quot;</span> <span class="na">aria-label=</span><span class="s">&quot;Back&quot;</span> <span class="na">disabled</span> <span class="na">type=</span><span class="s">&quot;button&quot;</span><span class="nt">&gt;&lt;/button&gt;</span>
</span><span class='line'>            <span class="nt">&lt;h1</span> <span class="na">class=</span><span class="s">&quot;titlearea win-type-ellipsis&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>                <span class="nt">&lt;span</span> <span class="na">class=</span><span class="s">&quot;pagetitle&quot;</span><span class="nt">&gt;</span>Welcome to duck<span class="nt">&lt;/span&gt;</span>
</span><span class='line'>            <span class="nt">&lt;/h1&gt;</span>
</span><span class='line'>        <span class="nt">&lt;/header&gt;</span>
</span><span class='line'>        <span class="nt">&lt;section</span> <span class="na">aria-label=</span><span class="s">&quot;Main content&quot;</span> <span class="na">role=</span><span class="s">&quot;main&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>            <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;content&quot;</span><span class="nt">&gt;</span>
</span><span class='line'><span class="nt">&lt;div</span> <span class="na">id=</span><span class="s">&quot;example_container&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>    <span class="nt">&lt;div</span> <span class="na">id=</span><span class="s">&quot;view_frame&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>        <span class="nt">&lt;div</span> <span class="na">id=</span><span class="s">&quot;scene&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>            <span class="nt">&lt;div</span> <span class="na">id=</span><span class="s">&quot;stars&quot;</span><span class="nt">&gt;&lt;/div&gt;</span>
</span><span class='line'>            <span class="nt">&lt;img</span> <span class="na">id=</span><span class="s">&quot;hubble&quot;</span> <span class="na">src=</span><span class="s">&quot;/images/hubble.png&quot;</span><span class="nt">/&gt;</span>
</span><span class='line'>            <span class="nt">&lt;img</span> <span class="na">id=</span><span class="s">&quot;earth&quot;</span> <span class="na">src=</span><span class="s">&quot;/images/mountain_earth.png&quot;</span><span class="nt">/&gt;</span>
</span><span class='line'>            <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;label hubble&quot;</span><span class="nt">&gt;</span>hubble<span class="nt">&lt;/div&gt;</span>
</span><span class='line'>            <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;label thermosphere&quot;</span><span class="nt">&gt;</span>thermosphere<span class="nt">&lt;/div&gt;</span>
</span><span class='line'>            <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;label mesosphere&quot;</span><span class="nt">&gt;</span>mesosphere<span class="nt">&lt;/div&gt;</span>
</span><span class='line'>            <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;label stratosphere&quot;</span><span class="nt">&gt;</span>stratosphere<span class="nt">&lt;/div&gt;</span>
</span><span class='line'>            <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;label troposphere&quot;</span><span class="nt">&gt;</span>troposphere<span class="nt">&lt;/div&gt;</span>
</span><span class='line'>            <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;label ozone&quot;</span><span class="nt">&gt;</span>ozone<span class="nt">&lt;/div&gt;</span>
</span><span class='line'>            <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;label crust&quot;</span><span class="nt">&gt;</span>crust<span class="nt">&lt;/div&gt;</span>
</span><span class='line'>            <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;label mantle&quot;</span><span class="nt">&gt;</span>mantle<span class="nt">&lt;/div&gt;</span>
</span><span class='line'>        <span class="nt">&lt;/div&gt;</span>
</span><span class='line'>    <span class="nt">&lt;/div&gt;</span>
</span><span class='line'>    <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;controls&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>        <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;intro-sentence&quot;</span><span class="nt">&gt;</span>From Earth to <span class="nt">&lt;a</span> <span class="na">id=</span><span class="s">&quot;a-hubble&quot;</span><span class="nt">&gt;</span>Hubble<span class="nt">&lt;/a&gt;&lt;/div&gt;</span>
</span><span class='line'>        <span class="nt">&lt;div</span> <span class="na">id=</span><span class="s">&quot;altitude_mark&quot;</span><span class="nt">&gt;&lt;/div&gt;</span>
</span><span class='line'>        <span class="nt">&lt;div</span> <span class="na">id=</span><span class="s">&quot;demo&quot;</span><span class="nt">&gt;&lt;/div&gt;</span>
</span><span class='line'>    <span class="nt">&lt;/div&gt;</span>
</span><span class='line'><span class="nt">&lt;/div&gt;</span>
</span><span class='line'><span class="nt">&lt;/div&gt;</span>
</span><span class='line'>    <span class="nt">&lt;/section&gt;</span>
</span><span class='line'>    <span class="nt">&lt;/div&gt;</span>
</span><span class='line'><span class="nt">&lt;/body&gt;</span>
</span><span class='line'>
</span><span class='line'><span class="nt">&lt;/html&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>If you were to run the app at this point, it would have a visually incomplete dial as illustrated:</p>

<p>   <img class="figure" alt="Figure 7-1" src="http://html5hacks.com/images/chapter-jeff/screen-4.png"></p>

<p>But how can that be you ask?  Have I lead you astray and YUI doesn’t really work in a Windows 8 App?  Not at all.  Remember how I mentioned that WinJS is constructing the pages for you.  In the process, they take the HTML content out of one HTML file and inject it into our main file (default.html).  What they don’t inject is the body tag.  This YUI example, for skinning purposes, has a class on the body tag, so we need to manually move that class to the body tag of our default.html file so it looks like this:</p>

<figure class='code'><figcaption><span>win8.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'>
</span><span class='line'>
</span><span class='line'><span class="nt">&lt;body</span> <span class="na">class=</span><span class="s">&quot;yui3-skin-sam&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>    <span class="nt">&lt;div</span> <span class="na">id=</span><span class="s">&quot;contenthost&quot;</span> <span class="na">data-win-control=</span><span class="s">&quot;Application.PageControlNavigator&quot;</span> <span class="na">data-win-options=</span><span class="s">&quot;{home: &#39;/pages/home/home.html&#39;}&quot;</span><span class="nt">&gt;&lt;/div&gt;</span>
</span><span class='line'>
</span><span class='line'><span class="nt">&lt;/body&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>When we reload our application with the new app, we have a skinned version of out dial:</p>

<p><img class="figure" alt="Figure 7-1" src="http://html5hacks.com/images/chapter-jeff/screen-5.png"></p>

<p>Now we’re all set to go.  Let’s go back to home.html and add a link to our new page:</p>

<figure class='code'><figcaption><span>win8.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'>
</span><span class='line'><span class="nt">&lt;p&gt;&lt;a</span> <span class="na">href=</span><span class="s">&quot;/pages/dial/dial.html&quot;</span> <span class="nt">&gt;</span>Dial<span class="nt">&lt;/a&gt;&lt;/p&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>At this point we’ll have a fully functional navigation app with two different YUI samples in the same Windows 8 App.</p>

<h2>Accessing Windows APIs with YUI</h2>

<p>One of the great things about being inside of a Windows 8 Store App is the access to the WinRT APIs.  There are a lot of cool platform features you can include, one of which is the share contract.  The share contract allows you to share data between apps.  In our case, we want to define what data will be passed to other apps when the user engages the share charm (part of the Windows 8 charms bar):</p>

<p><img class="figure" alt="Figure 7-1" src="http://html5hacks.com/images/chapter-jeff/screen-6.png"></p>

<p>In this case, I’m going to go into my sample code of the dial example code and add a few lines of JavaScript in:</p>

<figure class='code'><figcaption><span>win8.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>
</span><span class='line'>
</span><span class='line'><span class="kd">var</span> <span class="nx">dataTransferManager</span> <span class="o">=</span> <span class="nx">Windows</span><span class="p">.</span><span class="nx">ApplicationModel</span><span class="p">.</span><span class="nx">DataTransfer</span><span class="p">.</span><span class="nx">DataTransferManager</span><span class="p">.</span><span class="nx">getForCurrentView</span><span class="p">();</span>
</span><span class='line'><span class="nx">dataTransferManager</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s2">&quot;datarequested&quot;</span><span class="p">,</span> <span class="nx">shareTextHandler</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="kd">function</span> <span class="nx">shareTextHandler</span><span class="p">(</span><span class="nx">e</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>          <span class="kd">var</span> <span class="nx">request</span> <span class="o">=</span> <span class="nx">e</span><span class="p">.</span><span class="nx">request</span><span class="p">;</span>
</span><span class='line'>          <span class="nx">request</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">properties</span><span class="p">.</span><span class="nx">title</span> <span class="o">=</span> <span class="s2">&quot;Share Dial Level&quot;</span><span class="p">;</span>
</span><span class='line'>          <span class="nx">request</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">properties</span><span class="p">.</span><span class="nx">description</span> <span class="o">=</span> <span class="s2">&quot;I&#39;d like to share something with you&quot;</span><span class="p">;</span>
</span><span class='line'>     <span class="nx">request</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">setText</span><span class="p">(</span><span class="s2">&quot;Hello, my dial is set to &quot;</span> <span class="o">+</span> <span class="nx">dial</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="s1">&#39;value&#39;</span><span class="p">)</span> <span class="o">+</span> <span class="s2">&quot; Kilometers in altitude&quot;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>        <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>                <span class="nx">YUI</span><span class="p">.</span><span class="nx">namespace</span><span class="p">(</span><span class="s2">&quot;win8App&quot;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>                <span class="nx">YUI</span><span class="p">.</span><span class="nx">win8App</span><span class="p">.</span><span class="nx">sharePointer</span> <span class="o">=</span> <span class="nx">dataTransferManager</span><span class="p">;</span>
</span><span class='line'>                <span class="nx">YUI</span><span class="p">.</span><span class="nx">win8App</span><span class="p">.</span><span class="nx">shareFunction</span> <span class="o">=</span> <span class="nx">shareTextHandler</span><span class="p">;</span>
</span></code></pre></td></tr></table></div></figure>


<p>We set up a listener here for an event called “datarequested” in which we set properties of our data object.  At this point every app has declared (through the app manifest) what type of data can be shared to it.  In this method, we are simply declaring what type of data we are sharing.  In this case, we are setting text.  We also have a title and description that will be used by some apps.  Now, when we reload our app and navigate to our dial sample, we can select the “share charm” from our charm bar.  You’ll see a list of apps appear that are able to handle this type of shared content.</p>

<p><img class="figure" alt="Figure 7-1" src="http://html5hacks.com/images/chapter-jeff/screen-7.png"></p>

<p>I’ll select the mail app and you can see how this data will be shared:</p>

<p><img class="figure" alt="Figure 7-1" src="http://html5hacks.com/images/chapter-jeff/screen-8.png"></p>

<p>We are sharing info about our dial settings, so it doesn’t make sense to share that same data when we are viewing another sample, so we want to add a few additional lines of JavaScript to remove this listener when we don’t need it.  If you noticed above we used the YUI namespace to expose a pointer to both the function we are calling when we share, and a pointer to the dataTransfermanager itself.  We’re going to move down in our JavaScript object a bit to the “unload” method.  This method is called every time you navigate away from this page, so it will be a perfect place to remove this listener:</p>

<figure class='code'><figcaption><span>win8.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>
</span><span class='line'>
</span><span class='line'><span class="nx">unload</span><span class="o">:</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
</span><span class='line'>            <span class="c1">// TODO: Respond to navigations away from this page.</span>
</span><span class='line'>            <span class="nx">YUI</span><span class="p">.</span><span class="nx">win8App</span><span class="p">.</span><span class="nx">sharePointer</span><span class="p">.</span><span class="nx">removeEventListener</span><span class="p">(</span><span class="s2">&quot;datarequested&quot;</span><span class="p">,</span> <span class="nx">YUI</span><span class="p">.</span><span class="nx">win8App</span><span class="p">.</span><span class="nx">shareFunction</span><span class="p">);</span>
</span><span class='line'>        <span class="p">},</span>
</span></code></pre></td></tr></table></div></figure>


<p>More information about the share contract and other Windows APIs can be found here.</p>

<h2>Success!</h2>

<p>Well, we’ve done it.  We’ve built a Windows 8 Store App using YUI, we’ve mixed YUI with WinJS and were ready to roll.  I’ll add just a bit of CSS to my starting page to give it a bit of a metro feel and we’re all done.</p>

<h2>Conclusion</h2>

<p>To wrap up this whole experiment in a few works, it just works.  YUI works inside a Windows 8 Store App just as it would inside your browser.  The big difference is you now have access to all those Windows APIs that aren’t exposed to the web browser.  We’ve demonstrated how you can use YUI alongside of WinJS, but you don’t need to.  Your existing YUI app can be ported to Windows 8 Apps without needing WinJS.  It doesn’t stop at YUI, Windows 8 Apps are built on the engines that run IE10, so bring your favorite JavaScript library, your favorite YUI component or your favorite Web App and go “Native” with Windows 8.
The Key is to use the skills you already have, and the investments you’ve already made in your apps, and increase your reach in the Windows 8 Store.</p>

<h3>Posted by: <a href="http://twitter.com/boyofgreen">Jeff Burtoft</a></h3>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Build a Milestone Calendar with IndexedDB and FullCalendar.js]]></title>
    <link href="http://html5hacks.com/blog/2013/01/17/build-a-milestone-calendar-with-indexeddb-and-fullcalendar-dot-js/"/>
    <updated>2013-01-17T08:47:00-06:00</updated>
    <id>http://html5hacks.com/blog/2013/01/17/build-a-milestone-calendar-with-indexeddb-and-fullcalendar-dot-js</id>
    <content type="html"><![CDATA[<h4>IndexedDB is a persistent object data store in the browser. Although it is not a full SQL implementation and it is more complex than the unstructured key–value pairs in localStorage, you can use it to define an API that provides the ability to read and write key–value objects as structured JavaScript objects, and an indexing system that facilitates filtering and lookup.</h4>

<p>For this hack we will use IndexedDB to store milestone objects for a calendar application. The UI will provide a simple means to create a new milestone and provide a title, start date, and end date. The calendar will then update to show the contents of the local data store. Figure 6-8 shows the result.</p>

<p>Figure 6-8. FullCalendar.js and IndexedDB</p>

<p><img class="figure" alt="Figure 6-8" src="http://html5hacks.com/images/chapter6-images/6-8.png"></p>

<p>We need to start by including the markup for the two pieces of the UI: the calendar and the form.
We’ll begin with the form. You may notice that the input fields for the dates include data-date-format attributes. We will use these later for the JavaScript date pickers.</p>

<figure class='code'><figcaption><span>milestone form </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>&lt;form>
</span><span class='line'>     &lt;fieldset>
</span><span class='line'>
</span><span class='line'>       &lt;div class="control-group">
</span><span class='line'>         &lt;label class="control-label">Add a Milestone&lt;/label>
</span><span class='line'>         &lt;div class="controls">
</span><span class='line'>           &lt;h2>New Milestone&lt;/h2>
</span><span class='line'>           &lt;input type="text" name="title" value="">
</span><span class='line'>           &lt;input type="text" class="span2" name="start"
</span><span class='line'>             value="07/16/12" data-date-format="mm/dd/yy" id="dp1" >
</span><span class='line'>           &lt;input type="text" class="span2" name="end"
</span><span class='line'>             value="07/17/12"  data-date-format="mm/dd/yy" id="dp2" >
</span><span class='line'>         &lt;/div>
</span><span class='line'>       &lt;/div>
</span><span class='line'>
</span><span class='line'>       &lt;div class="form-actions">
</span><span class='line'>          &lt;button type="submit" class="btn btn-primary">Save&lt;/button>
</span><span class='line'>          &lt;button class="btn">Cancel&lt;/button>
</span><span class='line'>       &lt;/div>
</span><span class='line'>
</span><span class='line'>      &lt;/fieldset>
</span><span class='line'> &lt;/form></span></code></pre></td></tr></table></div></figure>


<p>The calendar is provided by <a href="http://arshaw.com/fullcalendar/">FullCalendar.js</a>, a fantastic jQuery plug-in for generating robust calendars from event sources. The library will generate a calendar from a configuration object and a simple div.</p>

<figure class='code'><figcaption><span>simple div </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>&lt;div id='calendar'>&lt;/div></span></code></pre></td></tr></table></div></figure>


<p>And we can’t forget to include a few dependencies:</p>

<figure class='code'><figcaption><span>CSS and JavaScript dependencies </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>&lt;link href="../assets/css/datepicker.css" rel="stylesheet">
</span><span class='line'>&lt;link href="../assets/css/fullcalendar.css" rel="stylesheet">
</span><span class='line'>
</span><span class='line'>&lt;script src="http://code.jquery.com/jquery-1.7.1.min.js">&lt;/script>
</span><span class='line'>&lt;script src="../assets/js/bootstrap-datepicker.js">&lt;/script>
</span><span class='line'>&lt;script src="../assets/js/fullcalendar.min.js">&lt;/script></span></code></pre></td></tr></table></div></figure>


<p>To improve the user experience, we will also include date pickers for choosing the dates within the form fields for start and end dates (see Figure 6-9).</p>

<p>Figure 6-9. Date pickers</p>

<p><img class="figure" alt="Figure 6-9" src="http://html5hacks.com/images/chapter6-images/6-9.png"></p>

<p>To instantiate the date pickers we will include the following toward the beginning of our script:</p>

<figure class='code'><figcaption><span>instantiate the date pickers </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>$(function(){
</span><span class='line'>    $('#dp1').datepicker();
</span><span class='line'>    $('#dp2').datepicker();
</span><span class='line'>  });</span></code></pre></td></tr></table></div></figure>


<h3>The Milestone IndexedDB</h3>

<p>Now we will set up a global namespace to hold our code, and set up a public milestones array (within the namespace) to hold our milestones temporarily while we pass them between our database and the FullCalendar API. This should make more sense as you continue to read. While we are at it we will need to normalize our indexedDB variable across all of the vendor-specific properties.</p>

<figure class='code'><figcaption><span>namespace and normalize </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>var html5hacks = {};
</span><span class='line'>
</span><span class='line'>html5hacks.msArray = [];
</span><span class='line'>
</span><span class='line'>var indexedDB = window.indexedDB || window.webkitIndexedDB ||
</span><span class='line'>                window.mozIndexedDB;
</span><span class='line'>
</span><span class='line'>if ('webkitIndexedDB' in window) {
</span><span class='line'>  window.IDBTransaction = window.webkitIDBTransaction;
</span><span class='line'>  window.IDBKeyRange = window.webkitIDBKeyRange;
</span><span class='line'>}
</span><span class='line'>Now we can begin to set up our database:
</span><span class='line'>html5hacks.indexedDB = {};
</span><span class='line'>html5hacks.indexedDB.db = null;
</span><span class='line'>
</span><span class='line'>function init() {
</span><span class='line'>  html5hacks.indexedDB.open();
</span><span class='line'>}
</span><span class='line'>
</span><span class='line'>init();</span></code></pre></td></tr></table></div></figure>


<p>This will obviously fail for now, but as you can see the initialization begins by calling the open() method on an html5hacks.indexedDB. So let’s take a closer look at open():</p>

<figure class='code'><figcaption><span>open() </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>html5hacks.indexedDB.open = function() {
</span><span class='line'>
</span><span class='line'>  var request = indexedDB.open("milestones");
</span><span class='line'>
</span><span class='line'>  request.onsuccess = function(e) {
</span><span class='line'>    var v = "1";
</span><span class='line'>    html5hacks.indexedDB.db = e.target.result;
</span><span class='line'>
</span><span class='line'>    var db = html5hacks.indexedDB.db;
</span><span class='line'>
</span><span class='line'>    if (v!= db.version) {
</span><span class='line'>      var setVrequest = db.setVersion(v);
</span><span class='line'>      setVrequest.onerror = html5hacks.indexedDB.onerror;
</span><span class='line'>
</span><span class='line'>      setVrequest.onsuccess = function(e) {
</span><span class='line'>        if(db.objectStoreNames.contains("milestone")) {
</span><span class='line'>          db.deleteObjectStore("milestone");
</span><span class='line'>        }
</span><span class='line'>
</span><span class='line'>        var store = db.createObjectStore("milestone",
</span><span class='line'>          {keyPath: "timeStamp"});
</span><span class='line'>
</span><span class='line'>        html5hacks.indexedDB.init();
</span><span class='line'>      };
</span><span class='line'>    }
</span><span class='line'>    else {
</span><span class='line'>      html5hacks.indexedDB.init();
</span><span class='line'>    }
</span><span class='line'>  };
</span><span class='line'>  request.onerror = html5hacks.indexedDB.onerror;
</span><span class='line'>}</span></code></pre></td></tr></table></div></figure>


<p>First, we need to open the database and pass a name. If the database successfully opens and a connection is made, the onsuccess() callback will be fired.</p>

<p>Within the onsuccess, we then check for a version and call setVersion() if one does not exist. Then we will call createObjectStore() and pass a unique timestamp within the keypath property.</p>

<p>Finally, we call init() to build the calendar and attach the events present in the database.</p>

<figure class='code'><figcaption><span>onsuccess() </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
<span class='line-number'>36</span>
<span class='line-number'>37</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>html5hacks.indexedDB.init = function() {
</span><span class='line'>
</span><span class='line'>  var db = html5hacks.indexedDB.db;
</span><span class='line'>  var trans = db.transaction(["milestone"], IDBTransaction.READ_WRITE);
</span><span class='line'>  var store = trans.objectStore("milestone");
</span><span class='line'>
</span><span class='line'>  var keyRange = IDBKeyRange.lowerBound(0);
</span><span class='line'>  var cursorRequest = store.openCursor(keyRange);
</span><span class='line'>
</span><span class='line'>  cursorRequest.onsuccess = function(e) {
</span><span class='line'>    var result = e.target.result;
</span><span class='line'>
</span><span class='line'>    if(!result == false){
</span><span class='line'>
</span><span class='line'>        $('#calendar').fullCalendar({
</span><span class='line'>          header: {
</span><span class='line'>            left: 'prev,next today',
</span><span class='line'>            center: 'title',
</span><span class='line'>            right: 'month,agendaWeek,agendaDay'
</span><span class='line'>          },
</span><span class='line'>          weekmode: 'variable',
</span><span class='line'>          height: 400,
</span><span class='line'>          editable: true,
</span><span class='line'>          events: html5hacks.msArray
</span><span class='line'>        });
</span><span class='line'>
</span><span class='line'>      return;
</span><span class='line'>
</span><span class='line'>    }else{
</span><span class='line'>
</span><span class='line'>      console.log("result.value" , result.value);
</span><span class='line'>      buildMilestoneArray(result.value);
</span><span class='line'>      result.continue();
</span><span class='line'>    }
</span><span class='line'>  };
</span><span class='line'>  cursorRequest.onerror = html5hacks.indexedDB.onerror;
</span><span class='line'>};</span></code></pre></td></tr></table></div></figure>


<p>At this point we are poised to retrieve all the data from the database and populate our calendar with milestones.
First, we declare the type of transaction to be a READ_WRITE, set a reference to the datastore, set a keyrange, and define a cursorRequest by calling openCursor and passing in the keyrange. By passing in a 0, we ensure that we retrieve all the values greater than zero. Since our key was a timestamp, this will ensure we retrieve all the records.</p>

<p>Once the onsuccess event is fired, we begin to iterate through the records and push the milestone objects to buildMilestoneArray:</p>

<figure class='code'><figcaption><span>buildMilestoneArray() </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>function buildMilestoneArray(ms) {
</span><span class='line'>  html5hacks.msArray.push(ms);
</span><span class='line'>}
</span><span class='line'>When we reach the last record, we build the calendar by passing a configuration object to fullCalendar() and returning:
</span><span class='line'>        $('#calendar').fullCalendar({
</span><span class='line'>          header: {
</span><span class='line'>            left: 'prev,next today',
</span><span class='line'>            center: 'title',
</span><span class='line'>            right: 'month,agendaWeek,agendaDay'
</span><span class='line'>          },
</span><span class='line'>          weekmode: 'variable',
</span><span class='line'>          height: 400,
</span><span class='line'>          editable: true,
</span><span class='line'>          events: html5hacks.msArray
</span><span class='line'>        });
</span><span class='line'>
</span><span class='line'>      return;</span></code></pre></td></tr></table></div></figure>


<h3>Adding Milestones</h3>

<p>Now that we are initializing and building our calendar, we need to begin adding milestones to the database via the form. First let’s use jQuery to set up our form to pass a serialized data object to addMilestone() on each submission:</p>

<figure class='code'><figcaption><span>form submit </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>$('form').submit(function() {
</span><span class='line'>
</span><span class='line'>    var data = $(this).serializeArray();
</span><span class='line'>
</span><span class='line'>    html5hacks.indexedDB.addMilestone(data);
</span><span class='line'>    return false;
</span><span class='line'>  });</span></code></pre></td></tr></table></div></figure>


<p>Now let’s submit a few events and then view them in the Chrome Inspector to ensure they are there (see Figure 6-10).</p>

<p>Figure 6-10. Viewing milestone objects in the Chrome Inspector</p>

<p><img class="figure" alt="Figure 6-10" src="http://html5hacks.com/images/chapter6-images/6-10.png"></p>

<p>Let’s take a closer look at our addMilestone method:</p>

<figure class='code'><figcaption><span>addMilestone() </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>html5hacks.indexedDB.addMilestone = function(d) {
</span><span class='line'>  var db = html5hacks.indexedDB.db;
</span><span class='line'>  var trans = db.transaction(["milestone"], IDBTransaction.READ_WRITE);
</span><span class='line'>  var store = trans.objectStore("milestone");
</span><span class='line'>
</span><span class='line'>  var data = {
</span><span class='line'>    "title": d[0].value,
</span><span class='line'>    "start": d[1].value,
</span><span class='line'>    "end": d[2].value,
</span><span class='line'>    "timeStamp": new Date().getTime()
</span><span class='line'>  };
</span><span class='line'>
</span><span class='line'>  var request = store.put(data);
</span><span class='line'>
</span><span class='line'>  var dataArr = [data]
</span><span class='line'>  request.onsuccess = function(e) {
</span><span class='line'>    $('#calendar').fullCalendar('addEventSource', dataArr);
</span><span class='line'>  };
</span><span class='line'>
</span><span class='line'>  request.onerror = function(e) {
</span><span class='line'>    console.log("Error Adding: ", e);
</span><span class='line'>  };
</span><span class='line'>};</span></code></pre></td></tr></table></div></figure>


<p>We established our read/write connection in much the same way as our html5hacks.indexedDB.init(), but now, instead of only reading data, we write a data object to the data store each time by calling store.put() and passing it data. On the onsuccess we then can call fullcalendar’s addEventSource() and pass it the data wrapped in an array object. Note that it is necessary to transform the data object into an array since that is what the FullCalendar API expects.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Make Your Web App Respond to Device Orientation Changes]]></title>
    <link href="http://html5hacks.com/blog/2013/01/04/make-your-web-app-respond-to-device-orientation-changes/"/>
    <updated>2013-01-04T00:31:00-06:00</updated>
    <id>http://html5hacks.com/blog/2013/01/04/make-your-web-app-respond-to-device-orientation-changes</id>
    <content type="html"><![CDATA[<h4>Your native apps are smart enough to know how you’re holding your device. Now your web apps can be, too. Use orientation-based media queries to make your site responsive.</h4>

<p>Mobile devices have brought a new paradigm to web development. Unlike desktops and laptops that have a fixed orientation (I rarely see people flip their PowerBook on its side), mobile devices can be viewed in either landscape or portrait mode. Most mobile phones and tablets have an accelerometer inside that recognizes the change in orientation and adjusts the screen accordingly. This allows you to view content on these devices in either aspect ratio. For example, the iPad has a screen aspect ratio of 3:4 where the device is taller than it is wide. When you turn it on its side, it has an aspect ratio of 4:3 (wider than it is tall). That’s an orientation change.</p>

<p>Using media queries, you can natively identify which orientation the device is being held in, and utilize different CSS for each orientation. Let’s go back to our example page and see what it would look like in landscape mode (see Figure 2-16) and portrait mode (see Figure 2-17).</p>

<p><img class="figure" alt="Figure 2-16" src="http://html5hacks.com/images/chapter2-images/2-15.png"></p>

<p>Figure 2-16:Our sample page in landscape mode on an iPad, with three columns of content</p>

<p>Here is the markup that makes each view work:</p>

<figure class='code'><figcaption><span>orientation.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;row&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>  <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;span4&quot;</span><span class="nt">&gt;</span>...<span class="nt">&lt;/div&gt;</span>
</span><span class='line'>  <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;span4&quot;</span><span class="nt">&gt;</span>...<span class="nt">&lt;/div&gt;</span>
</span><span class='line'>  <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;span4&quot;</span><span class="nt">&gt;</span>...<span class="nt">&lt;/div&gt;</span>
</span><span class='line'><span class="nt">&lt;/div&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Here is the CSS for the three-column view:</p>

<figure class='code'><figcaption><span>orientation.css </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='css'><span class='line'><span class="nc">.row</span> <span class="p">{</span>
</span><span class='line'>   <span class="k">width</span><span class="o">:</span> <span class="m">100</span><span class="o">%</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p><img class="figure" alt="Figure 2-17" src="http://html5hacks.com/images/chapter2-images/2-15b.png"></p>

<p>Figure 2-17: Our sample page in portrait mode on an iPad, with one column of linear content:</p>

<figure class='code'><figcaption><span>orientation.css </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='css'><span class='line'><span class="nc">.span4</span> <span class="p">{</span>
</span><span class='line'>   <span class="k">width</span><span class="o">:</span> <span class="m">300px</span><span class="p">;</span>
</span><span class='line'>   <span class="k">float</span><span class="o">:</span> <span class="k">left</span><span class="p">;</span>
</span><span class='line'>   <span class="k">margin-left</span><span class="o">:</span> <span class="m">30px</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>and the CSS for the single-column view:</p>

<figure class='code'><figcaption><span>orientation.css </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='css'><span class='line'><span class="nc">.row</span> <span class="p">{</span>
</span><span class='line'>   <span class="k">width</span><span class="o">:</span> <span class="m">100</span><span class="o">%</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'><span class="nc">.span4</span> <span class="p">{</span>
</span><span class='line'>   <span class="k">width</span><span class="o">:</span> <span class="k">auto</span><span class="p">;</span>
</span><span class='line'>   <span class="k">float</span><span class="o">:</span> <span class="k">none</span><span class="p">;</span>
</span><span class='line'>   <span class="k">margin</span><span class="o">:</span> <span class="m">0</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now we’ll wrap each CSS option in media queries so that they only apply in their proper orientation. Remember, the media queries wrap the CSS in conditions that only apply the declarations when the media query resolves to true. Using inline media queries, our CSS will now look something like this:</p>

<figure class='code'><figcaption><span>orientation.css </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
</pre></td><td class='code'><pre><code class='css'><span class='line'><span class="k">@media</span> <span class="nt">screen</span> <span class="nt">and</span> <span class="o">(</span><span class="nt">orientation</span><span class="nd">:landscape</span><span class="o">)</span> <span class="p">{</span>
</span><span class='line'><span class="nc">.row</span> <span class="p">{</span>
</span><span class='line'>   <span class="k">width</span><span class="o">:</span> <span class="m">100</span><span class="o">%</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'><span class="nc">.span4</span> <span class="p">{</span>
</span><span class='line'>   <span class="k">width</span><span class="o">:</span> <span class="m">300px</span><span class="p">;</span>
</span><span class='line'>   <span class="k">float</span><span class="o">:</span> <span class="k">left</span><span class="p">;</span>
</span><span class='line'>   <span class="k">margin-left</span><span class="o">:</span> <span class="m">30px</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'><span class="k">@media</span> <span class="nt">screen</span> <span class="nt">and</span> <span class="o">(</span><span class="nt">orientation</span><span class="nd">:portrait</span><span class="o">)</span> <span class="p">{</span>
</span><span class='line'><span class="nc">.row</span> <span class="p">{</span>
</span><span class='line'>   <span class="k">width</span><span class="o">:</span> <span class="m">100</span><span class="o">%</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'><span class="nc">.span4</span> <span class="p">{</span>
</span><span class='line'>   <span class="k">width</span><span class="o">:</span> <span class="k">auto</span><span class="p">;</span>
</span><span class='line'>   <span class="k">float</span><span class="o">:</span> <span class="k">none</span><span class="p">;</span>
</span><span class='line'>   <span class="k">margin</span><span class="o">:</span> <span class="m">0</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>With the CSS and media queries in place, our page will have three columns of content in landscape mode, and only one in portrait mode.</p>

<h2>Why Not Width?</h2>

<p>If you compare device orientation to max-width pixel media queries, you may realize you can accomplish this hack with max- and min-width queries, since the width will change when the device changes orientation. However, there are pros and cons to doing this.</p>

<p>Media queries based on orientation can often be simpler. You don’t need to know what screen size to expect for landscape versus portrait view. You simply rely on the orientation published by the device. You also gain consistency between devices in terms of how the pages appear in each orientation.</p>

<p>The argument against orientation media queries is pretty much the same. You really shouldn’t care if your orientation is portrait or landscape. If your screen width is 700px, it shouldn’t matter which way the device is being held: the layout should cater to a 700px screen. When you design for the available space the actual orientation becomes inconsequential.</p>

<p>Want to try it out?  View this code sample in our <a href="https://github.com/html5hacks/chapter2">GitHub Repo</a>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Elegantly Resize Your Page with the @-viewport CSS Declaration]]></title>
    <link href="http://html5hacks.com/blog/2012/11/28/elegantly-resize-your-page-with-the-at-viewport-css-declaration/"/>
    <updated>2012-11-28T18:37:00-06:00</updated>
    <id>http://html5hacks.com/blog/2012/11/28/elegantly-resize-your-page-with-the-at-viewport-css-declaration</id>
    <content type="html"><![CDATA[<h4>Gone are the days of viewport meta tags that with implementations different across browsers.  The new @-viewport is easy to use and puts the control in the right place.</h4>

<p>There is a minsconception that the meta “viewport” tag is a standard.  We have seen it implemeted in quite a few browsers, mostly mobile, and looks something like this:</p>

<figure class='code'><figcaption><span>meta.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;meta</span> <span class="na">name=</span><span class="s">&quot;viewport&quot;</span> <span class="na">content=</span><span class="s">&quot;width=320&quot;</span> <span class="nt">/&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Developers use this meta tag to control the zoom factor of the browser when loading the page.  If the above example, the page will assume that the viewport is 320px, no matter how many pixels are really available for rendering.  Usually, it was used to squeeze a 900-1200px screen, into a 320px screen.</p>

<p>The meta tag worked okay but it has limitations, and since it’s non-standard, it’s been implemented different ways across browsers.</p>

<h2>CSS Pixels</h2>

<p>To follow what&rsquo;s happening to your page with the viewport values, it’s important to understand the basic concept of viewport zooming.  I don’t think the explanation can be done any better than it was by PPK in <a href="http://www.quirksmode.org/mobile/viewports2.html">this post about viewports</a>.  Here’s the summary:</p>

<blockquote><p>Both viewports are measured in CSS pixels, obviously. But while the visual viewport dimensions change with zooming (if you zoom in, less CSS pixels fit on the screen), the layout viewport dimensions remain the same. (If they didn’t your page would constantly reflow as percentual widths are recalculated.)</p></blockquote>

<p>Let’s look at an example:</p>

<p><img class="figure" alt="Figure 7-1" src="http://html5hacks.com/images/news-images/viewport.png"></p>

<p>Two screenshots, the left used rendered in ie10 on windows phone 8 with no view port setting.  The screenshot on the right has a viewport declaration set to  set the viewport width to 320px</p>

<p>In the above figure, we see a smiley face on a page.   Both pages have a smiley face that has a width set to 300 pixels.  The difference is in css pixels.  Mobile browsers zoom out to see more content on a page by default.  In this case the page on the left is zoomed out so that the whole page can be seen.  This makes our smiley face much smaller that it actually is.  Although it may only take up 70 pixels of actual screen pixels, it’s  css pixel width will always be 300.</p>

<p>The figure on the right also is 300 css pixels, but since the viewport is set to 320px, the device pixels of the smiley face is actually 450 or so pixels.</p>

<h2>@-viewport CSS</h2>

<p>Sound difficult?  It’s going to get a lot simpler with a new specification.  The W3C has a specification to address the non-standard viewport meta tag and more, and the control has now rightfully been moved to CSS.</p>

<p>The specification can be found here:
  <a href="http://dev.w3.org/csswg/css-device-adapt/">http://dev.w3.org/csswg/css-device-adapt/</a></p>

<p>Although still in draft form, the specification has been implemented in Internet Explorer 10, and has developers quite excited about it.  Lets look at an example.  To set the screen to a CSS pixel width of 640 pixels, we would use the following css:</p>

<figure class='code'><figcaption><span>viewport.css </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='css'><span class='line'><span class="k">@-viewport</span> <span class="p">{</span>
</span><span class='line'><span class="nt">width</span><span class="o">:</span> <span class="nt">640px</span><span class="o">;</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Doesn’t that make sense?  The great thing is that this property works both ways (scaling up and down).  If you screen width is smaller than 640px, your screen will be zoomed out to fix the entire 640px viewport on the screen.  If you screen is larger than 640px, you screen will be zoomed in to only show 640px viewport.  In either case the css width of the screen is 640px.</p>

<p>Inside the viewport tag, you can set any value that is related to the viewport, specifically that means width, height, max-width, max-height, min-width, and min-height.  Widths and heights can be set to any of the these values:</p>

<ul>
<li>auto:  let the user agent determine the best</li>
<li>device width/height: scales to the actual width or height of the device.</li>
<li>percent/pixel value: specific settings to assume as the screen width or height.</li>
</ul>


<p>To maximize responsive design, you can use this @-viewport tag along with media queries, and may appear as something like the following:</p>

<figure class='code'><figcaption><span>viewport.css </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='css'><span class='line'><span class="k">@media</span> <span class="o">(</span><span class="nt">max-width</span><span class="o">:</span> <span class="nt">699px</span><span class="o">)</span> <span class="nt">and</span> <span class="o">(</span><span class="nt">min-width</span><span class="o">:</span> <span class="nt">520px</span><span class="o">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="k">@-viewport</span> <span class="p">{</span>
</span><span class='line'>    <span class="nt">width</span><span class="o">:</span> <span class="nt">640px</span><span class="o">;</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>The above css will normalize any screen smaller than 699px and larger than 520px to be rendered at a viewport of 640px.  This will save a boatload of other css properties to do this same feature.</p>

<p>In addition to the existing values, we have a few new values added as well, specifically the zoom value. Zoom allows us to set an initial zoom factor for the window or viewing area.  Zoom, along with min-zoom and max-zoom, can be set using any of the following values:</p>

<ul>
<li>auto: let the user agent determine the zoom factor</li>
<li>numeric: a positive integer that is used to determine the zoom value  A value of 1.0 has no zoom.</li>
<li>percentage: a positive percentage.  In the case of 100% there is no zoom.</li>
</ul>


<p>Zoom can be used by itself or in conjunction with a width or height value:</p>

<figure class='code'><figcaption><span>viewport.css </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='css'><span class='line'><span class="k">@-viewport</span> <span class="p">{</span>
</span><span class='line'>    <span class="nt">width</span><span class="o">:</span> <span class="nt">device-width</span><span class="o">;</span>
</span><span class='line'>    <span class="nt">zoom</span><span class="o">:</span> <span class="nc">.5</span><span class="o">;</span>
</span><span class='line'>  <span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>The second new descriptor is that of “orientation”.  Any keen developer can tell that this is used to request that your device lock in a specific orientation.  Any of the following keywords can be used:</p>

<ul>
<li>auto: let the user agent determin</li>
<li>landscape: lock the device in landscape orientation</li>
<li>portrait: lock the device in portrait mode</li>
</ul>


<p>The implementation can be used along with width and zoom as in the following example:</p>

<figure class='code'><figcaption><span>viewport.css </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='css'><span class='line'><span class="k">@viewport</span> <span class="p">{</span>
</span><span class='line'>    <span class="nt">width</span><span class="o">:</span> <span class="nt">980px</span><span class="o">;</span>
</span><span class='line'>    <span class="nt">min-zoom</span><span class="o">:</span> <span class="nt">0</span><span class="nc">.25</span><span class="o">;</span>
</span><span class='line'>    <span class="nt">max-zoom</span><span class="o">:</span> <span class="nt">5</span><span class="o">;</span>
</span><span class='line'>    <span class="nt">orientation</span><span class="o">:</span> <span class="nt">landscape</span><span class="o">;</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Internet Explorer Implementation</h2>

<p>The implementation in Internet Explorer 10 is practically identical to the W3C standard (great job IE team), with the addition of a prefix to signify that it’s an experimental implementation (as all prefixed implementations are).  The ie viewport value appears as follows:</p>

<figure class='code'><figcaption><span>viewport.css </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='css'><span class='line'><span class="k">@-ms-viewport</span> <span class="p">{</span>
</span><span class='line'>  <span class="nt">width</span><span class="o">:</span> <span class="nt">device-width</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>IEs implementation currently only supports the width and height properties. Min and max height/width are not implemented and neither are zoom or orientation.  As with all early implementation of standards, if the specification changes, I have no doubt that the internet explorer team with update the implementation to match the standard.</p>

<h2>Legacy Implementations</h2>

<p>When most developers think about viewport, this is what they think of:</p>

<figure class='code'><figcaption><span>meta.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;meta</span> <span class="na">name=</span><span class="s">&quot;viewport&quot;</span> <span class="na">content=</span><span class="s">&quot;width=320&quot;</span> <span class="nt">/&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>This tag zooms in the page to a viewport of 320 pixels.  Although originally introduced by apple most mobile browsers went on to support this tag in one form or another.  The tag was often supported differently from browser to browser, and the syntax was never really clear in its documentation.  hence, the need for a standard.</p>

<p>Different browses implemented the meta tag differently when using the meta tag to determine the width of the page (specifically by setting width to device-width)  Let’s look at the Windows Phone 7 Internet Explorer and iOS safari implementations.</p>

<h3>Internet explorer</h3>

<p>If you set the width in the meta tag to a specific size in internet explorer for windows phone 7, you get exactly what you ask for.  A meta tag like this:</p>

<figure class='code'><figcaption><span>meta.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;meta</span> <span class="na">name=</span><span class="s">&quot;viewport&quot;</span> <span class="na">content=</span><span class="s">&quot;width=480&quot;</span> <span class="nt">/&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>The above code will get you exactly what you ask for, which is a viewport zoomed to 480 pixels.  Now, when you set the width to be “device-width” such as the following:</p>

<figure class='code'><figcaption><span>meta.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;meta</span> <span class="na">name=</span><span class="s">&quot;viewport&quot;</span> <span class="na">content=</span><span class="s">&quot;width=device-width&quot;</span> <span class="nt">/&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>In this case, you get a page with a width of 320px in portrait mode, and 480px in landscape.  This is independent of how many pixels are actually available on the screen.</p>

<h3>Safari</h3>

<p>Safari on iOS works just like ie does for specific pixel settings, but differs when you set width to “device width”.  Let’s again look at our meta tag:</p>

<figure class='code'><figcaption><span>meta.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;meta</span> <span class="na">name=</span><span class="s">&quot;viewport&quot;</span> <span class="na">content=</span><span class="s">&quot;width=device-width&quot;</span> <span class="nt">/&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>In the case of iOS, the width of the screen will be set to the actual width of the screen.  If the screen has 640 pixels, than the viewport will be resized to 640 pixels.</p>

<p>One of the worst parts about this meta tag is it really only helps on smaller screen, where content needs to scale down in size.  it’s outdated and was due to be replace with something better.</p>

<p>The viewport standard is supported in ie10 on windows phone 8, but has legacy support for this meta tag as well.  Implementation of this meta tag in ie10 will give you the normalized values for page width (320px) when asking for screen size.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Make Your Page Consumable by Robots and Humans Alike with Microdata]]></title>
    <link href="http://html5hacks.com/blog/2012/11/21/make-your-page-consumable-by-robots-and-humans-alike-with-microdata/"/>
    <updated>2012-11-21T22:34:00-06:00</updated>
    <id>http://html5hacks.com/blog/2012/11/21/make-your-page-consumable-by-robots-and-humans-alike-with-microdata</id>
    <content type="html"><![CDATA[<p>HTML5 microdata provides the mechanism for easily allowing machines to consume the data on your pages, while not affecting the experience for the user.</p>

<p>If you’re like me, you believe that in the future, machines will rule over us humans with an iron fist (provided, of course, that the Zombie Apocalypse doesn’t get us first). While there isn’t anything we can do to help the zombie masses understand the Internet, HTML5 does offer a feature that prepares us for that machine dictatorship. It’s called microdata, and it’s supposed to be for machines only—no humans allowed.</p>

<p>You can tell by now that HTML5 adds a lot of depth to your data, but up to this point the focus has been on your users. Microdata takes you down a slightly different path when you think about consumers who aren’t your users. Microdata is additional context you add to your markup to make it more consumable. When you build your page, you can add these additional attributes to give further context to your markup.</p>

<p>Microdata can be added to any page element to identify that element as an “item” or a high-level chunk of data. The content nested inside that item can then be labeled as properties. These properties essentially become name–value pairs when the itemprop becomes the value name and the human-readable content becomes the value. The relevant code would look something like this:</p>

<figure class='code'><figcaption><span>scope.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;div</span> <span class="na">itemscope</span><span class="nt">&gt;</span>
</span><span class='line'>    <span class="nt">&lt;span</span> <span class="na">itemprop=</span><span class="s">&quot;name&quot;</span><span class="nt">&gt;</span>Fred<span class="nt">&lt;/span&gt;</span>
</span><span class='line'><span class="nt">&lt;/div&gt;</span>
</span><span class='line'>Sometimes item property data isn’t in the format that a “machine” would like, and additional attributes need to be added to clarify what the human-readable data is saying. In that scenario your data would look like this:
</span><span class='line'><span class="nt">&lt;div</span> <span class="na">itemscope</span><span class="nt">&gt;</span>
</span><span class='line'>    Hello, my name is <span class="nt">&lt;span</span> <span class="na">itemprop=</span><span class="s">&quot;name&quot;</span><span class="nt">&gt;</span>Fred<span class="nt">&lt;/span&gt;</span>.
</span><span class='line'>    I was born on
</span><span class='line'>   <span class="nt">&lt;time</span> <span class="na">itemprop=</span><span class="s">&quot;birthday&quot;</span> <span class="na">datetime=</span><span class="s">&quot;1975-09-29&quot;</span><span class="nt">&gt;</span>Sept. 29, 1975<span class="nt">&lt;/time&gt;</span>.
</span><span class='line'><span class="nt">&lt;/div&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now imagine how consumable the Web would be for those machines of the future once microdata is utilized on every page!</p>

<p>In this hack we’ll use microdata to make sure our contact list is machine-readable. Each contact entry will be identified as an item, and its contents will be labeled as a property. Our first contact will look like this:</p>

<figure class='code'><figcaption><span>scopeitem.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;li</span> <span class="na">itemscope</span><span class="nt">&gt;</span>
</span><span class='line'>    <span class="nt">&lt;ul&gt;</span>
</span><span class='line'>        <span class="nt">&lt;li&gt;</span>Name: <span class="nt">&lt;span</span> <span class="na">itemprop=</span><span class="s">&quot;name&quot;</span><span class="nt">&gt;</span>Fred<span class="nt">&lt;/span&gt;&lt;/li&gt;</span>
</span><span class='line'>        <span class="nt">&lt;li&gt;</span>Phone: <span class="nt">&lt;span</span> <span class="na">itemprop=</span><span class="s">&quot;telephone&quot;</span><span class="nt">&gt;</span>210-555-5555<span class="nt">&lt;/span&gt;&lt;/li&gt;</span>
</span><span class='line'>        <span class="nt">&lt;li&gt;</span>Email: <span class="nt">&lt;span</span> <span class="na">itemprop=</span><span class="s">&quot;email&quot;</span><span class="nt">&gt;</span>thebuffalo@rockandstone.com<span class="nt">&lt;/span&gt;&lt;/li&gt;</span>
</span><span class='line'>    <span class="nt">&lt;/ul&gt;</span>
</span><span class='line'><span class="nt">&lt;/li&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>As you can see, we have constructed one data item on our page, and when the markup is machine-read it will see the item as something like this:</p>

<figure class='code'><figcaption><span>json.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>    <span class="nx">Item</span><span class="o">:</span> <span class="p">{</span>    <span class="nx">name</span><span class="o">:</span> <span class="s1">&#39;Fred&#39;</span><span class="p">,</span>
</span><span class='line'>        <span class="nx">telephone</span><span class="o">:</span> <span class="s1">&#39;210-555-5555&#39;</span><span class="p">,</span>
</span><span class='line'>        <span class="nx">email</span><span class="o">:</span> <span class="s1">&#39;thebuffalo@rockandstone.com&#39;</span>
</span><span class='line'>        <span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now let’s build ourselves a whole list:</p>

<figure class='code'><figcaption><span>wholelist.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;ul&gt;</span>
</span><span class='line'><span class="nt">&lt;li</span> <span class="na">itemscope</span><span class="nt">&gt;</span>
</span><span class='line'>    <span class="nt">&lt;ul&gt;</span>
</span><span class='line'>        <span class="nt">&lt;li&gt;</span>Name: <span class="nt">&lt;span</span> <span class="na">itemprop=</span><span class="s">&quot;name&quot;</span><span class="nt">&gt;</span>Fred<span class="nt">&lt;/span&gt;&lt;/li&gt;</span>
</span><span class='line'>        <span class="nt">&lt;li&gt;</span>Phone: <span class="nt">&lt;span</span> <span class="na">itemprop=</span><span class="s">&quot;telephone&quot;</span><span class="nt">&gt;</span>210-555-5555<span class="nt">&lt;/span&gt;&lt;/li&gt;</span>
</span><span class='line'>        <span class="nt">&lt;li&gt;</span>Email: <span class="nt">&lt;span</span> <span class="na">itemprop=</span><span class="s">&quot;email&quot;</span><span class="nt">&gt;</span>thebuffalo@rockandstone.com<span class="nt">&lt;/span&gt;&lt;/li&gt;</span>
</span><span class='line'>    <span class="nt">&lt;/ul&gt;</span>
</span><span class='line'><span class="nt">&lt;/li&gt;</span>
</span><span class='line'><span class="nt">&lt;li</span> <span class="na">itemscope</span><span class="nt">&gt;</span>
</span><span class='line'>    <span class="nt">&lt;ul&gt;</span>
</span><span class='line'>        <span class="nt">&lt;li&gt;</span>Name: <span class="nt">&lt;span</span> <span class="na">itemprop=</span><span class="s">&quot;name&quot;</span><span class="nt">&gt;</span>Wilma<span class="nt">&lt;/span&gt;&lt;/li&gt;</span>
</span><span class='line'>        <span class="nt">&lt;li&gt;</span>Phone: <span class="nt">&lt;span</span> <span class="na">itemprop=</span><span class="s">&quot;telephone&quot;</span><span class="nt">&gt;</span>210-555-7777<span class="nt">&lt;/span&gt;&lt;/li&gt;</span>
</span><span class='line'>        <span class="nt">&lt;li&gt;</span>Email: <span class="nt">&lt;span</span> <span class="na">itemprop=</span><span class="s">&quot;email&quot;</span><span class="nt">&gt;</span>thewife@rockandstone.com<span class="nt">&lt;/span&gt;&lt;/li&gt;</span>
</span><span class='line'>    <span class="nt">&lt;/ul&gt;</span>
</span><span class='line'><span class="nt">&lt;/li&gt;</span>
</span><span class='line'><span class="nt">&lt;li</span> <span class="na">itemscope</span><span class="nt">&gt;</span>
</span><span class='line'>    <span class="nt">&lt;ul&gt;</span>
</span><span class='line'>        <span class="nt">&lt;li&gt;</span>Name: <span class="nt">&lt;span</span> <span class="na">itemprop=</span><span class="s">&quot;name&quot;</span><span class="nt">&gt;</span>Betty<span class="nt">&lt;/span&gt;&lt;/li&gt;</span>
</span><span class='line'>        <span class="nt">&lt;li&gt;</span>Phone: <span class="nt">&lt;span</span> <span class="na">itemprop=</span><span class="s">&quot;telephone&quot;</span><span class="nt">&gt;</span>210-555-8888<span class="nt">&lt;/span&gt;&lt;/li&gt;</span>
</span><span class='line'>        <span class="nt">&lt;li&gt;</span>Email: <span class="nt">&lt;span</span> <span class="na">itemprop=</span><span class="s">&quot;email&quot;</span><span class="nt">&gt;</span>theneighbour@rockandstone.com<span class="nt">&lt;/span&gt;&lt;/li&gt;</span>
</span><span class='line'>    <span class="nt">&lt;/ul&gt;</span>
</span><span class='line'><span class="nt">&lt;/li&gt;</span>
</span><span class='line'><span class="nt">&lt;li</span> <span class="na">itemscope</span><span class="nt">&gt;</span>
</span><span class='line'>    <span class="nt">&lt;ul&gt;</span>
</span><span class='line'>        <span class="nt">&lt;li&gt;</span>Name: <span class="nt">&lt;span</span> <span class="na">itemprop=</span><span class="s">&quot;name&quot;</span><span class="nt">&gt;</span>Barny<span class="nt">&lt;/span&gt;&lt;/li&gt;</span>
</span><span class='line'>        <span class="nt">&lt;li&gt;</span>Phone: <span class="nt">&lt;span</span> <span class="na">itemprop=</span><span class="s">&quot;telephone&quot;</span><span class="nt">&gt;</span>210-555-0000<span class="nt">&lt;/span&gt;&lt;/li&gt;</span>
</span><span class='line'>        <span class="nt">&lt;li&gt;</span>Email: <span class="nt">&lt;span</span> <span class="na">itemprop=</span><span class="s">&quot;email&quot;</span><span class="nt">&gt;</span>thebestfriend@rockandstone.com<span class="nt">&lt;/span&gt;&lt;/li&gt;</span>
</span><span class='line'>    <span class="nt">&lt;/ul&gt;</span>
</span><span class='line'><span class="nt">&lt;/li&gt;</span>
</span><span class='line'><span class="nt">&lt;/ul&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>To our human friends the page looks something like Figure 1-14.</p>

<p><img class="figure" alt="Figure 1-14" src="http://html5hacks.com/images/chapter1-images/microdata1.jpg"></p>

<p>Figure 1-14. Adding microdata to the page, which does not change the view for users</p>

<p>To our machine friends, the code looks something like this:</p>

<figure class='code'><figcaption><span>itemjson.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>    <span class="nx">Item</span><span class="o">:</span> <span class="p">{</span>    <span class="nx">name</span><span class="o">:</span> <span class="s1">&#39;Fred&#39;</span><span class="p">,</span>
</span><span class='line'>        <span class="nx">telephone</span><span class="o">:</span> <span class="s1">&#39;210-555-5555&#39;</span><span class="p">,</span>
</span><span class='line'>        <span class="nx">email</span><span class="o">:</span> <span class="s1">&#39;thebuffalo@rockandstone.com&#39;</span>
</span><span class='line'>        <span class="p">},</span>
</span><span class='line'>    <span class="nx">Item</span><span class="o">:</span> <span class="p">{</span>    <span class="nx">name</span><span class="o">:</span> <span class="s1">&#39;Wilma&#39;</span><span class="p">,</span>
</span><span class='line'>        <span class="nx">telephone</span><span class="o">:</span> <span class="s1">&#39;210-555-7777&#39;</span><span class="p">,</span>
</span><span class='line'>        <span class="nx">email</span><span class="o">:</span> <span class="s1">&#39;thewife@rockandstone.com&#39;</span>
</span><span class='line'>        <span class="p">},</span>
</span><span class='line'>    <span class="nx">Item</span><span class="o">:</span> <span class="p">{</span>    <span class="nx">name</span><span class="o">:</span> <span class="s1">&#39;Betty&#39;</span><span class="p">,</span>
</span><span class='line'>        <span class="nx">telephone</span><span class="o">:</span> <span class="s1">&#39;210-555-8888&#39;</span><span class="p">,</span>
</span><span class='line'>        <span class="nx">email</span><span class="o">:</span> <span class="s1">&#39;theneighbor@rockandstone.com&#39;</span>
</span><span class='line'>        <span class="p">},</span>
</span><span class='line'>    <span class="nx">Item</span><span class="o">:</span> <span class="p">{</span>    <span class="nx">name</span><span class="o">:</span> <span class="s1">&#39;Barny,</span>
</span><span class='line'><span class="s1">        telephone: &#39;</span><span class="mi">210</span><span class="o">-</span><span class="mi">555</span><span class="o">-</span><span class="mi">0000</span><span class="s1">&#39;,</span>
</span><span class='line'><span class="s1">        email: &#39;</span><span class="nx">thebestfriend</span><span class="err">@</span><span class="nx">rockandstone</span><span class="p">.</span><span class="nx">com</span><span class="err">&#39;</span>
</span><span class='line'>        <span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>It’s that easy to add microdata to your page without sacrificing the interface for your human friends.</p>

<h2>Details, Details!</h2>

<p>Microdata is pretty darn easy to implement, and the W3C spec thinks it should be just as easy to read, which is why the W3C added a JavaScript API to be able to access the data. Remember each of your identified elements was marked with an attribute called itemscope, which means the API considers them items. To get all these items, you simply call the following:</p>

<figure class='code'><figcaption><span>getitem.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nb">document</span><span class="p">.</span><span class="nx">getItems</span><span class="p">();</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now your items can also be segmented by type, so you can identify some of your items as people, and others as cats. Microdata allows you to define your items by adding the itemtype attribute, which will point to a URL, or have an inline definition. In this case, if we defined our cat type by referring to the URL <a href="http://example.com/feline,">http://example.com/feline,</a> our cat markup would look something like this:</p>

<figure class='code'><figcaption><span>More lastscope.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;li</span> <span class="na">itemscope</span> <span class="na">itemtype=</span><span class="s">&quot;http://example.com/feline&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>    <span class="nt">&lt;ul&gt;</span>
</span><span class='line'>        <span class="nt">&lt;li&gt;</span>Name: <span class="nt">&lt;span</span> <span class="na">itemprop=</span><span class="s">&quot;name&quot;</span><span class="nt">&gt;</span>Dino<span class="nt">&lt;/span&gt;&lt;/li&gt;</span>
</span><span class='line'>        <span class="nt">&lt;li&gt;</span>Phone: <span class="nt">&lt;span</span> <span class="na">itemprop=</span><span class="s">&quot;telephone&quot;</span><span class="nt">&gt;</span>210-555-4444<span class="nt">&lt;/span&gt;&lt;/li&gt;</span>
</span><span class='line'>        <span class="nt">&lt;li&gt;</span>Email: <span class="nt">&lt;span</span> <span class="na">itemprop=</span><span class="s">&quot;email&quot;</span><span class="nt">&gt;</span>thecat@rockandstone.com<span class="nt">&lt;/span&gt;&lt;/li&gt;</span>
</span><span class='line'>    <span class="nt">&lt;/ul&gt;</span>
</span><span class='line'><span class="nt">&lt;/li&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>And if we wanted to get items with only a specific type of cat, we would call:</p>

<figure class='code'><figcaption><span>getsample.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="nb">document</span><span class="p">.</span><span class="nx">getItems</span><span class="p">(</span><span class="s2">&quot;http://example.com/feline&quot;</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>Thanks to this simple API, your microdata-enriched markup is both easy to produce and easy to consume.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Configure Amazon S3 for Cross Origin Resourse Sharing to Host a Web Font]]></title>
    <link href="http://html5hacks.com/blog/2012/11/18/configure-amazon-s3-for-cross-origin-resourse-sharing-to-host-a-web-font/"/>
    <updated>2012-11-18T19:42:00-06:00</updated>
    <id>http://html5hacks.com/blog/2012/11/18/configure-amazon-s3-for-cross-origin-resourse-sharing-to-host-a-web-font</id>
    <content type="html"><![CDATA[<p>Cross-Origin Resource Sharing (CORS) is a specification that allows applications to
make requests to other domains from within the browser. With CORS you have a secure
and easy-to-implement approach for circumventing the browser’s same origin
policy.</p>

<p>In this hack we will explore hosting a web font on a cloud drive. In order to do so, we
will learn how to configure an Amazon S3 bucket to accept requests from other domains.</p>

<p>If you are not already familiar with web fonts and @font-face, refer to Hack #12.</p>

<p>In the next section I provide a bit more background on Amazon S3 and the same origin
policy, before we get into the details of CORS.</p>

<h3>What Is an Amazon S3 Bucket?</h3>

<p>Amazon S3 (Simple Storage Service) is simply a cloud drive. Files of all kinds can be
stored using this service, but web application developers often use it to store static
assets such as images, JavaScript files, and stylesheets.</p>

<p>For performance improvements, web developers like to employ Content Delivery Networks
(CDNs) to serve their static files. While Amazon S3 is not a CDN in and of itself,
it’s easy to activate it as one by using CloudFront.</p>

<p>A bucket refers to the directory name that you choose to store your static files.
To get started let’s set up an account at Amazon and navigate to the Amazon Management
Console; see Figure 9-21.</p>

<p>Figure 9-21. S3 Management Console</p>

<p><img class="figure" alt="Figure 9-21" src="http://html5hacks.com/images/chapter9-images/9-21.png"></p>

<p>If we click on Create a Bucket we should see the prompt shown in Figure 9-22.</p>

<p>Figure 9-22. Creating an S3 bucket in the S3 Management Console</p>

<p><img class="figure" alt="Figure 9-22" src="http://html5hacks.com/images/chapter9-images/9-22.png"></p>

<p>Let’s name the bucket and choose a region (see Figure 9-23). As I stated earlier, you
can choose a region to optimize for latency, minimize costs, or address regulatory
requirements.</p>

<p>Figure 9-23. Naming an S3 bucket in the S3 Management Console</p>

<p><img class="figure" alt="Figure 9-23" src="http://html5hacks.com/images/chapter9-images/9-23.png"></p>

<p>We will go ahead and name our bucket none other than “html5hacks.” You should now
see an admin screen that shows an empty filesystem (see Figure 9-24).</p>

<p>Figure 9-24. The html5hacks S3 bucket</p>

<p><img class="figure" alt="Figure 9-24" src="http://html5hacks.com/images/chapter9-images/9-24.png"></p>

<p>Well, that was simple. So why are we doing this? Let’s start with some simple browser
security—something called the same origin policy.</p>

<h3>Same Origin Policy</h3>

<p>As the browser becomes more and more of an application platform, application developers
have compelling reasons to write code that makes requests to other domains
in order to interact directly with the content. Wikipedia defines same origin policy as
follows:</p>

<p>In computing, the same origin policy is an important security concept for a
number of browser-side programming languages, such as JavaScript. The
policy permits scripts running on pages originating from the same site to
access each other’s methods and properties with no specific restrictions,
but prevents access to most methods and properties across pages on different
sites.1</p>

<p>1 <a href="http://en.wikipedia.org/wiki/Same_origin_policy">http://en.wikipedia.org/wiki/Same_origin_policy</a></p>

<p>As stated in Wikipedia’s definition, the same origin policy is a good thing; it protects
the end user from security attacks. But it does cause some challenges for web developers.</p>

<p>This is where CORS comes into the picture. CORS allows developers of remote data
and content to designate which domains (through a whitelist) can interact with their
content.</p>

<h3>Using Web Fonts in Your Application</h3>

<p>There are a number of ways to use a web font within your web pages, such as calling
the @font-face service, bundling the font within your application, hosting the web font
in your own Amazon S3 bucket (more on this later), or converting the file to Base64
and embedding the data inline in a data-uri. By the way, the last technique is similar
to the one outlined in Hack #13.</p>

<p>Each of these techniques has limitations.</p>

<ul>
<li>When calling the @font-face service you are limited to the fonts within the particular
service’s database.</li>
<li>Bundling the font within your application does not make use of HTTP caching, so
your application will continue to download the font file on every page request.
Furthermore, you cannot reuse the font within other applications.</li>
<li>Hosting the font in an Amazon S3 bucket works great, except with Firefox, which
enforces the same origin policy on all resources. So the response from the remote
server will be denied.</li>
<li>Converting the font to Base64 adds additional weight to the stylesheet, and does
not take advantage of caching.</li>
</ul>


<p>An exploration into the different types of web fonts is beyond the scope of this hack,
so I will assume that you have already selected the web font BebasNeue.otf.
You can download free and open fonts from sites such as <a href="http://www.dafont.com.">http://www.dafont.com.</a></p>

<h3>Uploading Your Font to Your Amazon S3 Bucket</h3>

<p>Now, all we have to do is to upload the font onto our filesystem in the cloud (see
Figure 9-25).</p>

<p>Figure 9-25. An uploaded BebasNeue font</p>

<p><img class="figure" alt="Figure 9-25" src="http://html5hacks.com/images/chapter9-images/9-25.png"></p>

<h3>Adding the Web Font to Your Web Page</h3>

<p>In order to add a web font to our page, we need to add a single stylesheet to an HTML
page.</p>

<p>Here is our page. Let’s call it index.html, and add a <link> tag pointing to our base
stylesheet, styles.css.</p>

<figure class='code'><figcaption><span>geo.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;html&gt;</span>
</span><span class='line'>  <span class="nt">&lt;head&gt;</span>
</span><span class='line'>    <span class="nt">&lt;title&gt;</span>S3 - font<span class="nt">&lt;/title&gt;</span>
</span><span class='line'>    <span class="nt">&lt;meta</span> <span class="na">charset=</span><span class="s">&quot;utf-8&quot;</span> <span class="nt">/&gt;</span>
</span><span class='line'>    <span class="nt">&lt;link</span> <span class="na">rel=</span><span class="s">&quot;stylesheet&quot;</span> <span class="na">type=</span><span class="s">&quot;text/css&quot;</span> <span class="na">href=</span><span class="s">&quot;styles.css&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>  <span class="nt">&lt;/head&gt;</span>
</span><span class='line'>  <span class="nt">&lt;body&gt;</span>
</span><span class='line'>    <span class="nt">&lt;h1</span> <span class="na">class=</span><span class="s">&quot;test&quot;</span><span class="nt">&gt;</span>HTML5 Hacks<span class="err">&lt;</span>/&gt;
</span><span class='line'>  <span class="nt">&lt;/body&gt;</span>
</span><span class='line'><span class="nt">&lt;/html&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>In our styles.css let’s add the following and point to our uploaded file. Also, let’s assign
the font to our H1 header via the test class name.</p>

<figure class='code'><figcaption><span>style.css </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='css'><span class='line'><span class="k">@font-face</span> <span class="p">{</span>
</span><span class='line'>  <span class="nt">font-family</span><span class="o">:</span> <span class="nt">BebasNeue</span><span class="o">;</span>
</span><span class='line'>  <span class="nt">src</span><span class="o">:</span> <span class="nt">url</span><span class="o">(</span><span class="s1">&#39;https://s3.amazonaws.com/html5hacks/BebasNeue.otf&#39;</span><span class="o">);</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="nc">.test</span> <span class="p">{</span>
</span><span class='line'>  <span class="k">font-family</span><span class="o">:</span> <span class="s1">&#39;BebasNeue&#39;</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now we’ll open a browser and point to our newly created HTML page. In Opera (see
Figure 9-26), Safari, and Chrome our header tag is being styled correctly.</p>

<p>Figure 9-26. Opera browser showing the BebasNeue font</p>

<p><img class="figure" alt="Figure 9-26" src="http://html5hacks.com/images/chapter9-images/9-26.png"></p>

<p>But if we view it in Firefox, we are having issues (see Figure 9-27).</p>

<p>Figure 9-27. Firefox browser failing to show the BebasNeue font</p>

<p><img class="figure" alt="Figure 9-27" src="http://html5hacks.com/images/chapter9-images/9-27.png"></p>

<p>If we examine the request for our font in the Chrome Dev Tools Network tab, we will
see that the response from the server is empty (see Figure 9-28).</p>

<p>Figure 9-28. Firefox browser showing an empty response</p>

<p><img class="figure" alt="Figure 9-28" src="http://html5hacks.com/images/chapter9-images/9-28.png"></p>

<p>What gives? Well, by default, Firefox will only accept links from the same domain as
the host page. If we want to include fonts from different domains, we need to add an
Access-Control-Allow-Origin header to the font.</p>

<p>So, if you try to serve fonts from any CDN, Firefox will not load them.</p>

<h3>What Is CORS?</h3>

<p>The CORS specification uses the XMLHttpRequest object to send and receive headers
from the originating web page to a server that is properly configured in order to
enable cross-site requests.</p>

<p>The server accepting the request must respond with the
Access-Control-Allow-Origin header with either a wildcard (*) or the correct
origin domain sent by the originating web page as the value. If the value is not included,
the request will fail.</p>

<p>Furthermore, for HTTP methods other than GET or POST, such as PUT, a preflight request
is necessary, in which the browser sends an HTTP OPTIONS request to establish
a handshake with the server before accepting the PUT request.</p>

<p>Fortunately, after enough backlash from the development community, Amazon made
CORS configuration available on Amazon S3 via a very simple XML configuration.</p>

<p>Let’s get started.</p>

<h3>Configuring CORS at Amazon S3</h3>

<p>You should already be at your Amazon Management Console at <a href="http://">http://</a>
console.aws.amazon.com. Click on Properties→Permissions→Edit CORS configuration,
and you should receive a modal prompt.</p>

<p>The configuration can accept up to 100 rule definitions, but for our web font we will
only need a few. For this example we will use the wildcard, but if you are doing this in
production, you should whitelist the domains to prevent others from serving your font
from your S3 account on their own web pages. It wouldn’t be the end of the world, but
it might get costly.</p>

<p>The first rule allows cross-origin GET requests from any origin. The rule also allows all
headers in a preflight OPTIONS request through the
Access-Control-Request-Headers header. In response to any preflight OPTIONS
request, Amazon S3 will return any requested headers.</p>

<p>The second rule allows cross-origin GET requests from all origins. The * wildcard
character refers to all origins.</p>

<figure class='code'><figcaption><span>config.xml </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='xml'><span class='line'><span class="nt">&lt;CORSConfiguration&gt;</span>
</span><span class='line'><span class="nt">&lt;CORSRule&gt;</span>
</span><span class='line'><span class="nt">&lt;AllowedOrigin&gt;</span>*/AllowedOrigin&gt;
</span><span class='line'><span class="nt">&lt;AllowedMethod&gt;</span>GET<span class="nt">&lt;/AllowedMethod&gt;</span>
</span><span class='line'><span class="nt">&lt;/CORSRule&gt;</span>
</span><span class='line'><span class="nt">&lt;/CORSConfiguration&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>So, let’s add our new configuration to our Editor and save (see Figure 9-29).</p>

<p>Figure 9-29. Configuring CORS in the S3 Management Console</p>

<p><img class="figure" alt="Figure 9-29" src="http://html5hacks.com/images/chapter9-images/9-29.png"></p>

<p>Now, let’s return to Firefox and reload the page. We should now see the header font
styled with our BebasNeue web font, as shown in Figure 9-30.</p>

<p>Figure 9-30. Firefox browser successfully showing the BebasNeue font</p>

<p><img class="figure" alt="Figure 9-30" src="http://html5hacks.com/images/chapter9-images/9-30.png"></p>

<p>There is much more to learn about CORS, most notably, HTTP POST usage with certain
MIME types, and sending cookies and HTTP authentication data with requests if so
requested by the CORS-enabled server. So get out there and starting creating your
own CORS hacks.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Overview of the GeoLocation Chapter in O'Reilly HTML5 Hacks]]></title>
    <link href="http://html5hacks.com/blog/2012/10/15/overview-of-the-geolocation-chapter-in-oreilly-html5-hacks/"/>
    <updated>2012-10-15T23:19:00-05:00</updated>
    <id>http://html5hacks.com/blog/2012/10/15/overview-of-the-geolocation-chapter-in-oreilly-html5-hacks</id>
    <content type="html"><![CDATA[<p>An exploration of the future of web technologies and browser capabilities would not be complete without covering the tools and techniques available to enable location awareness.</p>

<p>Location-aware web applications provide content, functionality, and services based on the cooperative detection of the user’s physical location. These applications can then provide the user with real-time filtering of online information relevant to his current location, such as place markers indicating the user’s location within a map, local consumer reviews, local coupons and offers, and even relevant traffic and public transportation notices.</p>

<p>These applications also enable users to provide their location to friends in a social network and vice versa, creating possibilities for meetups and blended online and physical interaction.</p>

<p>As you might imagine, the opportunities are not just limited to enhancing the life of the consumer. Given real-time location data of potential consumers and their friends, retailers can also create highly targeted, location-specific marketing campaigns for both digital and physical products.</p>

<h2>How Does It Work?</h2>

<p>The web browser employs various technologies to pass parameters via a background HTTP request to a Location Information Server that returns a data set that includes an estimated longitude and latitude.</p>

<p>The technologies used to gather location data depend on the device and on the operating system running on the device. The most common sources are:</p>

<ul>
<li>Public IP address</li>
<li>WiFi access points</li>
<li>Bluetooth MAC IDs</li>
<li>GPS</li>
<li>GSM/CDMA cell tower IDs</li>
</ul>


<p>Geolocation libraries for the Web are not new. In fact, today’s W3C Geolocation specification is largely reflective of the original Google Gears API introduced by Google in 2008. The API has been standardized and is one of the most widely adopted of the HTML5 specifications covered in this book (O&#8217;Reilly HTML5 Hacks).</p>

<p>Fortunately, the API is also easy to use—a benefit we will explore in “Use the Geolocation APIs to Display Longitude and Latitude in a Mobile Web Application” and “Update a User’s Current Location in a Google Map”.</p>

<p>In addition, a number of third-party services are available for creating really interesting hacks, and they explore concepts such as reverse geocoding and geofencing. In “Use Google’s Geocoding API to Reverse-Geocode a User’s Location” and “Use the Geoloqi Service to Build a Geofence” we will pass our location data to a service that will provide an enhanced API for working with location data.
In “Use the Geoloqi Real-Time Streaming Service to Broadcast a Remote User’s Movement” we will blend the power of the WebSocket API with location awareness to make our application update in real time.</p>

<p>For browsers that don’t provide this functionality natively, Google’s IP geocoding service can serve as a polyfill, as we will explore in “Polyfill Geolocation APIs with Webshims”.</p>

<p>The main drawback to this functionality is related to privacy and security, and for good reason. After all, as responsible application developers we should be doing what we can to protect the sensitive data of our users. In “Use the Geolocation APIs to Display Longitude and Latitude in a Mobile Web Application” we will take an in-depth look at how the browser employs cooperative detection, allowing the user to opt-in to only sharing location data with trusted web applications.</p>

<p>Want to read more detail? &hellip; <a href="http://shop.oreilly.com/product/0636920026273.do?sortby=bestSellers">buy the book</a>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Use the GeoLocation API to Display Long/Lat in a jQuery Mobile App]]></title>
    <link href="http://html5hacks.com/blog/2012/10/15/use-the-geolocation-api-to-display-long-slash-lat-in-a-jquery-mobile-app/"/>
    <updated>2012-10-15T23:15:00-05:00</updated>
    <id>http://html5hacks.com/blog/2012/10/15/use-the-geolocation-api-to-display-long-slash-lat-in-a-jquery-mobile-app</id>
    <content type="html"><![CDATA[<p>The Geolocation specification exposes an easy-to-use API. With only a couple of lines of code, you can obtain the user’s current position. What’s more, jQuery Mobile provides a simple framework for building a cross-browser mobile web application.</p>

<p>In this hack we will utilize the jQuery Mobile framework to provide a relatively simple means of authoring a cross-browser mobile application. Since this hack is focused on displaying our current longitude and latitude and exercising the API across the mobile Web, we will only need a simple UI.</p>

<h3>A Simple jQuery Mobile App</h3>

<p>As always, we’ll start by building a basic page utilizing the HTML5 doctype and including our dependencies:</p>

<figure class='code'><figcaption><span>geo.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="cp">&lt;!DOCTYPE html&gt;</span>
</span><span class='line'><span class="nt">&lt;html</span> <span class="na">lang=</span><span class="s">&quot;en&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>    <span class="nt">&lt;head&gt;</span>
</span><span class='line'>        <span class="nt">&lt;title&gt;</span>jQuery Mobile GeoLocation demo<span class="nt">&lt;/title&gt;</span>
</span><span class='line'>        <span class="nt">&lt;meta</span> <span class="na">name=</span><span class="s">&quot;viewport&quot;</span> <span class="na">content=</span><span class="s">&quot;width=device-width, initial-scale=1&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>
</span><span class='line'>        <span class="nt">&lt;link</span> <span class="na">rel=</span><span class="s">&quot;stylesheet&quot;</span> <span class="na">href=</span><span class="s">&quot;http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.css&quot;</span> <span class="nt">/&gt;</span>
</span><span class='line'>
</span><span class='line'>        <span class="nt">&lt;script </span><span class="na">src=</span><span class="s">&quot;http://code.jquery.com/jquery-1.7.1.min.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'>
</span><span class='line'>        <span class="nt">&lt;script </span><span class="na">src=</span><span class="s">&quot;http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.js&quot;</span><span class="nt">&gt;&lt;/script&gt;</span>
</span><span class='line'>
</span><span class='line'>    <span class="nt">&lt;/head&gt;</span>
</span><span class='line'><span class="nt">&lt;body&gt;</span>
</span><span class='line'>
</span><span class='line'>    // jQuery mobile declarative markup here
</span><span class='line'>
</span><span class='line'><span class="nt">&lt;/body&gt;</span>
</span><span class='line'><span class="nt">&lt;/html&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>As you can see, we have declared a dependency on one stylesheet, and three JavaScripts. We will build the remainder of the application using declarative HTML markup and data- attributes that the jQuery Mobile framework will interpret.<br/>
Within the <body> tag, we can now place the following:</p>

<figure class='code'><figcaption><span>More geo.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;div</span> <span class="na">data-role=</span><span class="s">&quot;page&quot;</span> <span class="na">data-theme=</span><span class="s">&quot;a&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>
</span><span class='line'>    <span class="nt">&lt;div</span> <span class="na">data-role=</span><span class="s">&quot;header&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>        <span class="nt">&lt;h1&gt;</span>Geo Location<span class="nt">&lt;/h1&gt;</span>
</span><span class='line'>    <span class="nt">&lt;/div&gt;</span><span class="c">&lt;!-- /header --&gt;</span>
</span><span class='line'>
</span><span class='line'>    <span class="nt">&lt;div</span> <span class="na">data-role=</span><span class="s">&quot;content&quot;</span><span class="nt">&gt;</span>  
</span><span class='line'>        <span class="nt">&lt;ul</span> <span class="na">data-role=</span><span class="s">&quot;listview&quot;</span> <span class="na">data-inset=</span><span class="s">&quot;true&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>            <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">&quot;./longlat-embed.html&quot;</span> <span class="na">data-ajax=</span><span class="s">&quot;false&quot;</span><span class="nt">&gt;</span>LongLat<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
</span><span class='line'>        <span class="nt">&lt;/ul&gt;</span>
</span><span class='line'>    <span class="nt">&lt;/div&gt;</span><span class="c">&lt;!-- /content --&gt;</span>
</span><span class='line'>
</span><span class='line'><span class="nt">&lt;/div&gt;</span><span class="c">&lt;!-- /page --&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>At this point you should see what’s shown in Figure 7-1, if you access this page from a smaller screen or shrink your desktop browser window to the size of a mobile browser.</p>

<p>Figure 7-1. jQuery Mobile simple button</p>

<p><img class="figure" alt="Figure 7-1" src="http://html5hacks.com/images/chapter7-images/7-1.png"></p>

<p>As you might expect, the UI wasn’t created through magic. jQuery Mobile uses JavaScript to consume the data- attributes present in your HTML markup to dynamically generate more HTML and CSS. The end result is what you see in your browser.
Now we will create a separate page to link to. You many have noticed a link to longlat-embed.html within the main page.</p>

<figure class='code'><figcaption><span>More geo.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'> <span class="nt">&lt;ul</span> <span class="na">data-role=</span><span class="s">&quot;listview&quot;</span> <span class="na">data-inset=</span><span class="s">&quot;true&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>      <span class="nt">&lt;li&gt;&lt;a</span> <span class="na">href=</span><span class="s">&quot;./longlat-embed.html&quot;</span> <span class="na">data-ajax=</span><span class="s">&quot;false&quot;</span><span class="nt">&gt;</span>LongLat<span class="nt">&lt;/a&gt;&lt;/li&gt;</span>
</span><span class='line'>  <span class="nt">&lt;/ul&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>This will take us to a page that will run our JavaScript that contains our geolocation code. Notice that we designated for this to not be a jQuery Mobile Ajax page. This ensures that upon the click of the link we navigate to the new page. It is important that the linked page is loaded so that its JavaScript will execute.</p>

<p>This page is structured similarly to the other page, with the same dependencies. I intentionally kept the jQuery Mobile code as simple as possible. You can find more information on working with jQuery Mobile in the excellent set of <a href="http://jquerymobile.com/demos/1.1.1/">documentation</a> .</p>

<figure class='code'><figcaption><span>More geo.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'><span class="nt">&lt;div</span> <span class="na">data-role=</span><span class="s">&quot;page&quot;</span> <span class="na">data-theme=</span><span class="s">&quot;a&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>
</span><span class='line'>    <span class="nt">&lt;div</span> <span class="na">data-role=</span><span class="s">&quot;header&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>        <span class="nt">&lt;h1&gt;</span>LongLat<span class="nt">&lt;/h1&gt;</span>
</span><span class='line'>    <span class="nt">&lt;/div&gt;</span><span class="c">&lt;!-- /header --&gt;</span>
</span><span class='line'>
</span><span class='line'>        <span class="nt">&lt;div</span> <span class="na">data-role=</span><span class="s">&quot;content&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>
</span><span class='line'>        <span class="nt">&lt;/div&gt;</span><span class="c">&lt;!-- /content --&gt;</span>
</span><span class='line'>
</span><span class='line'><span class="nt">&lt;/div&gt;</span><span class="c">&lt;!-- /page --&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>In the content, we will create a div element that will contain our longitude and latitude data once it is returned from the remote service. We will also include a back capability to return to the previous page.</p>

<figure class='code'><figcaption><span>More geo.html </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='html'><span class='line'>    <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;geo-coords&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>        GeoLocation: <span class="nt">&lt;span</span> <span class="na">id=</span><span class="s">&quot;Lat&quot;</span><span class="nt">&gt;</span>lat: ...<span class="nt">&lt;/span&gt;</span>°,
</span><span class='line'>               <span class="nt">&lt;span</span> <span class="na">id=</span><span class="s">&quot;Long&quot;</span><span class="nt">&gt;</span>long: ...<span class="nt">&lt;/span&gt;</span>°
</span><span class='line'>    <span class="nt">&lt;/div&gt;</span>
</span><span class='line'>
</span><span class='line'>    <span class="nt">&lt;a</span> <span class="na">href=</span><span class="s">&quot;./jqueryMobile-embed.html&quot;</span>
</span><span class='line'>       <span class="na">data-role=</span><span class="s">&quot;button&quot;</span>
</span><span class='line'>       <span class="na">data-inline=</span><span class="s">&quot;true&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>        Back
</span><span class='line'>    <span class="nt">&lt;/a&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now we will address our geolocation JavaScript. If you are familiar with jQuery the initial $ variable will look familiar in the code that follows. If not, you can learn more about jQuery at <a href="http://docs.jquery.com/Main_Page.">http://docs.jquery.com/Main_Page.</a></p>

<p>Simply put, the jQuery function wrapper ensures that our page is ready before we execute the following script. Then we will set up a global namespace object that we will use to store our data. This type of organization will be important as our script gets more complex moving forward.</p>

<p>Next, we will check to make sure the current browser supports geolocation by checking the navigator object for the presence of the geolocation property. If it is available, we will call the getCurrentPosition method and pass a success and error object.
Then we will construct both a success and error object. Within our success object we can accept a position as a parameter and query the object for its nested coords object which contains both latitude and longitude properties.</p>

<p>We will then call populateHeader(), which uses jQuery to append the returned values to the span tags that contain the IDs Lat and Long.</p>

<figure class='code'><figcaption><span>geo.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>    <span class="nx">$</span><span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>
</span><span class='line'>        <span class="kd">var</span> <span class="nx">Geo</span><span class="o">=</span><span class="p">{};</span>
</span><span class='line'>
</span><span class='line'>        <span class="k">if</span> <span class="p">(</span><span class="nx">navigator</span><span class="p">.</span><span class="nx">geolocation</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>           <span class="nx">navigator</span><span class="p">.</span><span class="nx">geolocation</span><span class="p">.</span><span class="nx">getCurrentPosition</span><span class="p">(</span><span class="nx">success</span><span class="p">,</span> <span class="nx">error</span><span class="p">);</span>
</span><span class='line'>        <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>        <span class="c1">//Get the latitude and the longitude;</span>
</span><span class='line'>        <span class="kd">function</span> <span class="nx">success</span><span class="p">(</span><span class="nx">position</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>            <span class="nx">Geo</span><span class="p">.</span><span class="nx">lat</span> <span class="o">=</span> <span class="nx">position</span><span class="p">.</span><span class="nx">coords</span><span class="p">.</span><span class="nx">latitude</span><span class="p">;</span>
</span><span class='line'>            <span class="nx">Geo</span><span class="p">.</span><span class="nx">lng</span> <span class="o">=</span> <span class="nx">position</span><span class="p">.</span><span class="nx">coords</span><span class="p">.</span><span class="nx">longitude</span><span class="p">;</span>
</span><span class='line'>            <span class="nx">populateHeader</span><span class="p">(</span><span class="nx">Geo</span><span class="p">.</span><span class="nx">lat</span><span class="p">,</span> <span class="nx">Geo</span><span class="p">.</span><span class="nx">lng</span><span class="p">);</span>
</span><span class='line'>        <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>        <span class="kd">function</span> <span class="nx">error</span><span class="p">(){</span>
</span><span class='line'>            <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s2">&quot;Geocoder failed&quot;</span><span class="p">);</span>
</span><span class='line'>        <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>        <span class="kd">function</span> <span class="nx">populateHeader</span><span class="p">(</span><span class="nx">lat</span><span class="p">,</span> <span class="nx">lng</span><span class="p">){</span>
</span><span class='line'>            <span class="nx">$</span><span class="p">(</span><span class="s1">&#39;#Lat&#39;</span><span class="p">).</span><span class="nx">html</span><span class="p">(</span><span class="nx">lat</span><span class="p">);</span>
</span><span class='line'>            <span class="nx">$</span><span class="p">(</span><span class="s1">&#39;#Long&#39;</span><span class="p">).</span><span class="nx">html</span><span class="p">(</span><span class="nx">lng</span><span class="p">);</span>
</span><span class='line'>        <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now let’s return to our browser and navigate to the new page. When a user accesses a web page that includes a call to navigator.geolocation.getCurrentPosition(), a security notification bar will be presented at the top of the page. Browsers that support the Geolocation API have their own security notification, which asks the user to allow or deny the browser access to the device’s current location (see Figure 7-2).</p>

<p>Figure 7-2. Google Chrome geolocation security notification</p>

<p><img class="figure" alt="Figure 7-2" src="http://html5hacks.com/images/chapter7-images/7-2.png"></p>

<p>If the user allows the web application to track her physical location, the script will continue to execute and make a request to the Location Information Server. The remote server returns a data set that includes longitude and latitude. Once we have the information and the success() callback has been called, we update the page (see Figure 7-3).</p>

<p>Figure 7-3. Latitude and longitude</p>

<p><img class="figure" alt="Figure 7-3" src="http://html5hacks.com/images/chapter7-images/7-3.png"></p>

<h3>Security and Privacy Concerns</h3>

<p>The ability for web application developers to collect location data about end users raises quite a bit of concern in regard to security and privacy. The W3C specification clearly indicates that client applications should notify users and provide an interface to authorize the use of location data, allowing them to determine which web applications they trust:</p>

<p>User agents must not send location information to Web sites without the express permission of the user. User agents must acquire permission through a user interface, unless they have prearranged trust relationships with users, as described below. The user interface must include the host component of the document&rsquo;s URI [URI]. Those permissions that are acquired through the user interface and that are preserved beyond the current browsing session (i.e. beyond the time when the browsing context [BROWSINGCONTEXT] is navigated to another URL) must be revocable and user agents must respect revoked permissions.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Web Workers: Basics of the Web Browser's UI Thread]]></title>
    <link href="http://html5hacks.com/blog/2012/09/22/web-workers-basics-of-the-web-browsers-ui-thread/"/>
    <updated>2012-09-22T23:44:00-05:00</updated>
    <id>http://html5hacks.com/blog/2012/09/22/web-workers-basics-of-the-web-browsers-ui-thread</id>
    <content type="html"><![CDATA[<h2>Single Threadin&#8217;</h2>

<p>As we set out to build a highly responsive UI for our demo web application, we must fully understand how browsers manage processes. Perhaps the biggest challenge we will face has to do with browsers using a single thread for both JavaScript execution and user interface updates. While the browser&rsquo;s JavaScript interpreter is executing code, the UI is unable to respond to the user&rsquo;s input. If a script is taking a long time to complete, after a specified amount of time the browser will provide the user an option to terminate the script. To accommodate for the &lsquo;freeze&rsquo; associated with scripts that exceed the browser execution time limit, web developers have traditionally created smaller units of work and used JavaScript timers to return execution to the next event in the queue. As you will see, web workers solve the locking of the UI thread by opening an additional thread, or even multiple threads, for execution of these long running, processor intensive tasks.</p>

<p>When designing your application, especially if you come from more of a &lsquo;server-side&rsquo; or Java background, it is important to understand that non-blocking execution is not the same as concurrent threading. While not extremely complex, JavaScript&rsquo;s event driven style does take some getting used to for developers coming from other languages such as Java and C. Later, we will touch on a few examples where we pass a callback continuation function to take full advantage of JavaScript&rsquo;s non blocking design.</p>

<h2>Thread Safety</h2>

<p>Mozilla, in particular, provides a Worker interface which web workers implement. While the Worker interface spawns OS-level threads, web workers use the postMessage mechanism to send messages (with serializable objects) between the two execution contexts. To ensure thread safety the worker is only given access to thread safe components to include the following:</p>

<ul>
<li>timers: setTimeout() and setInterval() methods</li>
<li>XMLHttpRequest</li>
<li>importScripts() method</li>
</ul>


<p>The worker script can also make use of:</p>

<ul>
<li>navigator and location objects</li>
<li>native JavaScript objects such as Object, String, Date</li>
</ul>


<p>At the same time, the worker restricts access to DOM APIs, global variables, and the parent page. In Hack #84 Building the DOM with web workers and Handlebars.js, we will explore the restricted access to DOM APIs, and introduce JavaScript templating, importScripts, and the use of timers to poll for postMessage.</p>

<h2>HTML5 Web Workers</h2>

<p>As mentioned earlier, the Web worker spec defines an API for executing scripts in the background by spawning an independent execution context.</p>

<p>It is important to note that web workers are costly, having an impact on startup and overall memory consumption. So, they are intended to be used lightly and in conjunction with the some of the asynchronous techniques mentioned earlier. A well built client-side application would typically make use of one or two cases where tasks are expensive. Here are a few common uses cases:</p>

<ul>
<li>Single Page Application bootstrapping large amounts of data during initial load</li>
<li>Performing long running mathematical calculations in the browser</li>
<li>Processing large JSON datasets</li>
<li>Text formatting, spell checking, and syntax highlighting</li>
<li>Processing multimedia data (Audio/Video)</li>
<li>Long polling webservices</li>
<li>Filtering images in canvas</li>
<li>Calculating points for a 3D image</li>
<li>Reading/Writing of local storage database</li>
</ul>


<h2>Long Running Scripts</h2>

<p>Our first web worker hack will be a long running script with heavy computation. It will execute 2 loops that output a two-dimensional array. First, we will use this computation to lock up the browser&rsquo;s UI thread, and later we will move the task to a worker.</p>

<figure class='code'><figcaption><span>init.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>   
</span><span class='line'>  <span class="kd">function</span> <span class="nx">init</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>      <span class="kd">var</span> <span class="nx">r</span> <span class="o">=</span> <span class="mi">1000</span><span class="p">;</span>
</span><span class='line'>      <span class="kd">var</span> <span class="nx">c</span> <span class="o">=</span> <span class="mi">1000</span><span class="p">;</span>
</span><span class='line'>      <span class="kd">var</span> <span class="nx">a</span> <span class="o">=</span> <span class="k">new</span> <span class="nb">Array</span><span class="p">(</span><span class="nx">r</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>      <span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="nx">i</span> <span class="o">&lt;</span> <span class="nx">r</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>          <span class="nx">a</span><span class="p">[</span><span class="nx">i</span><span class="p">]</span> <span class="o">=</span> <span class="k">new</span> <span class="nb">Array</span><span class="p">(</span><span class="nx">c</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>          <span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">j</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="nx">j</span> <span class="o">&lt;</span> <span class="nx">c</span><span class="p">;</span> <span class="nx">j</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>              <span class="nx">a</span><span class="p">[</span><span class="nx">i</span><span class="p">][</span><span class="nx">j</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;[&quot;</span> <span class="o">+</span> <span class="nx">i</span> <span class="o">+</span> <span class="s2">&quot;,&quot;</span> <span class="o">+</span> <span class="nx">j</span> <span class="o">+</span> <span class="s2">&quot;]&quot;</span><span class="p">;</span>
</span><span class='line'>          <span class="p">}</span>
</span><span class='line'>      <span class="p">}</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'>  
</span><span class='line'>  <span class="nb">window</span><span class="p">.</span><span class="nx">onload</span> <span class="o">=</span> <span class="nx">init</span><span class="p">;</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Spawning a Worker</h2>

<p>Now let&rsquo;s move our heavy computational task to a dedicated web worker, so that the user doesn&rsquo;t have to wait for the script to complete execution in order to interact with user interface. First, lets spawn a new worker:</p>

<figure class='code'><figcaption><span>spawn.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">worker</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Worker</span><span class="p">(</span><span class="s1">&#39;highComp.js&#39;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">worker</span><span class="p">.</span><span class="nx">postMessage</span><span class="p">(</span><span class="nx">JSON</span><span class="p">.</span><span class="nx">stringify</span><span class="p">(</span><span class="nx">message</span><span class="p">));</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">worker</span><span class="p">.</span><span class="nx">addEventListener</span><span class="p">(</span><span class="s1">&#39;message&#39;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">event</span><span class="p">){},</span> <span class="kc">false</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>Here, we define an external file that will contain the logic of our heavy computational task. The file, highComp.js will listen for a message that will receive the serialized JSON payload, and then we will set up an additional listener to receive a message back from highComp.js.</p>

<p>Now, we can move this cpu-intensive task to a separate file: highComp.js</p>

<figure class='code'><figcaption><span>highComp.js </span></figcaption>
 <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="kd">var</span> <span class="nx">r</span> <span class="o">=</span> <span class="mi">1000</span><span class="p">;</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">c</span> <span class="o">=</span> <span class="mi">1000</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'><span class="kd">var</span> <span class="nx">a</span> <span class="o">=</span> <span class="k">new</span> <span class="nb">Array</span><span class="p">(</span><span class="nx">r</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="nx">i</span> <span class="o">&lt;</span> <span class="nx">r</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>  <span class="nx">a</span><span class="p">[</span><span class="nx">i</span><span class="p">]</span> <span class="o">=</span> <span class="k">new</span> <span class="nb">Array</span><span class="p">(</span><span class="nx">c</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">j</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="nx">j</span> <span class="o">&lt;</span> <span class="nx">c</span><span class="p">;</span> <span class="nx">j</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>     <span class="nx">a</span><span class="p">[</span><span class="nx">i</span><span class="p">][</span><span class="nx">j</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;[&quot;</span> <span class="o">+</span> <span class="nx">i</span> <span class="o">+</span> <span class="s2">&quot;,&quot;</span> <span class="o">+</span> <span class="nx">j</span> <span class="o">+</span> <span class="s2">&quot;]&quot;</span><span class="p">;</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">};</span>
</span><span class='line'><span class="nx">postMessage</span><span class="p">(</span><span class="nx">a</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>In highComp.js, our two dimensional array is built and set to variable a. It is then passed back to our main script via the postMessage call.</p>

<p>In the next hack, we will mix our use of timers with the power of a dedicated worker. As we send messages (passing serializable objects as a parameter to postMessage) back and forth to code running in the shared UI thread, our timer will periodically send and check for new messages and use their contents to modify the DOM.</p>
]]></content>
  </entry>
  
</feed>
