HTML5 Hacks

Hacking Next Generation Web Technologies

Add Narration to Your Slide Deck With HTML5 Audio

| Comments

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.

Sample Example

To show what we’re trying to accomplish, I’ve created a very basic slide deck with audio narration which briefly describes the issue at hand.

Audio on the Web

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

Luckily for us, <bgsound> isn’t the end of the story. According to the latest W3C spec, <bgsound> has a much friendlier HTML5 alternative that you’ve likely heard of: the <audio> tag.

So what benefits does <audio> bring us? Well, <bgsound> was an IE only property. <audio> on the other hand has wide support, with only IE 7 & 8 lacking functionality. <audio> also allows API access so that we can control playback, seek through the audio, and even manipulate the data with the MediaStream API. Plus, the <audio> tag allows you to use native controls and/or provide your own customized controls.

File formats

Before getting in to the details on how we’re going to use the <audio> 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’s for our audio is a messy situation.

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

For our needs, we’ve created two files: an MP4/AAC file and an OggVorbis file.

If you’d like to read more on the subject, I highly recommend Ashley Gullen’s post ‘On HTML5 audio formats – AAC and Ogg’.

How to Use It?

We can load our audio files by adding in two <source> tags with information about our two audio files inside of the <audio> tag:

index.html
1
2
3
4
5
<audio controls id="myPlayer">
  <source src="myAudio.m4a" type="audio/mp4" />
  <source src="myAudio.ogg" type="audio/ogg"  />
  Your browser does not support HTML5 audio.
</audio>

There are two attributes for each <source> tag. The ‘src’ attribute, whose value is the path to the audio file, and the ‘type’ attribute, whose value is the MIME type of the file.

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

Starting/Stopping

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

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

audio.js
1
2
3
var audioPlayer = document.getElementById('myPlayer');
audioPlayer.play();
audioPlayer.pause();

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

Seeking

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 ‘currentTime’ property that can be both get and set (in seconds).

audio.js
1
2
3
4
5
6
7
8
9
console.log(audioPlayer.currentTime); // returns 0 since we haven't started playing the audio yet
audioPlayer.currentTime = 10; // move to 10 seconds into the audio
console.log(audioPlayer.currentTime); // returns 10

audioPlayer.play();

setTimeout(function () {
  console.log(audioPlayer.currentTime); // returns 11
}, 1000);

As you can see, getting and setting the current time is a trivial process. In the Part 2, we’ll put this functionality to use by adding narration to slides.

Implementing Slide Narration

So now we’ve got the building blocks for implementing a slide narrator. To make things easier, we’re going to use the fantastic ‘Deck.js’ project as our HTML slide framework. Deck.js supports extensions, which allows you to add functionality to your slides beyond what’s already provided.

We’ll be creating a new extension called Narrator. For brevity’s sake, I won’t get into the details of Deck.js or creating extensions, but you can check out the code in the deck.narrator.js GitHub repo.

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

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

  • How will we define what audio to play for each slide?
  • How will we stop the audio after it gets to the end of the section

Defining Audio Stops

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’ll just define how long each slide should play for, and then calculate the implied start and stop timestamps for each slide.

To store our audio duration, we’ll take advantage of HTML5 data-* attributes by creating a custom ‘data-narrator-duration’ attribute. The value of this will be the number of seconds to play the audio for. Here’s a sample slide element for a Deck.js HTML file.

index.html
1
2
3
<section class="slide" data-narrator-duration="2">
  ...
</section>

Then, upon page initialization, we’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’s the basic code:

deck.narrator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// create an array for our segment timestamps 
var segments = [];

// create a placeholder for our audio element reference 
var audio;

// we'll get to this variable later
var segmentEnd = 0;

function init () {
  // get the audio element we added to our page
  audio = document.getElementById('audioNarration');

  // use deck.js built-in functionality to get all slides and current slide
  var $slides = $.deck('getSlides');
  var $currentSlide = $.deck('getSlide');

  // set initial values for time position and index
  var position = 0;
  var currentIndex = 0;

  // now loop through each slide
  $.each($slides, function(i, $el) {
    // get the duration specified from the HTML element
    var duration = $el.data('narrator-duration');

    // this determines which slide the viewer loaded the page on
    if ($currentSlide == $el) {
      currentIndex = i;
    }

    // push the start time (previous position) and end time (position + duration) to an array of slides
    segments.push([position, position + duration]);

    // increment the position to the start of the next slide
    position += duration;
  });
}

Adding Playback Automatically on Slide Change

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

deck.narrator.js
1
2
3
4
5
6
7
8
9
10
function changeSlides (e, from, to) {
  // check to make sure audio element has been found
  if(audio) {
    // move the playback to our slides start
    audio.currentTime = segments[to][0];

    // define the end of our section
    segmentEnd = segments[to][1];
  }
}

Most of the code makes sense, but I do want to talk about the ‘segmentEnd’ line and what it’s doing.

Playing Segments of Audio

Unfortunately, you can’t give the play() 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 ‘timeupdate’ 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:

deck.narrator.js
1
audio.addEventListener('timeupdate', checkTime, false);

Our ‘checkTime’ 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:

deck.narrator.js
1
2
3
4
5
function checkTime () {
  if (audio.currentTime >= segmentEnd) {
    audio.pause();
  }
}

Automatically Moving Through Slides

Now that we’ve got our audio hooked up to our slides, we can take advantage of the other extensions already written for Deck.js. https://github.com/rchampourlier/deck.automatic.js/‎ is an extension that makes your slides run automatically. By including this extension with our presentation, we can recreate that ‘presentation’ feel to our slides.

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’ll sync up the ‘play’ and ‘pause’ events of our audio element with the automatic extension. For simplicity, we’re going to control all slide playback using our audio controls and leave off the deck.automatic.js playback control.

Deck.automatic.js adds some events to the mix, including ‘play’ and ‘pause’ events. By triggering these events when our similarly named audio events fire, we can make sure our slides are in sync with our content.

We add two simple functions to our extension:

deck.narrator.js
1
2
3
4
5
6
7
function startSlides (ev) {
  $.deck('play');
}

function stopSlides (ev) {
  $.deck('pause');
}

And then add our event listeners in the deck.init callback:

deck.narrator.js
1
2
3
4
5
6
7
8
9
$d.bind('deck.init', function() {

  // ... other code here ...

  // Sync audio with slides
  audio.addEventListener('play', startSlides, false);
  audio.addEventListener('pause', stopSlides, false);

});

Also, since our slides automatically advance, we need to comment out the ‘timeupdate’ event listener which would pause our audio at the end of a slide.

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

Next Steps

One thing the code doesn’t take into consideration is if the user navigation the audio themselves. We could add this by listening to the ‘seeked’ event from the audio element and calculating where in the slide deck we should move to.

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.

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 new track tag that can handle this for us, so that’s a likely route we can go down.

Summing Up

That’s the majority of the code. I left out a few details in relation to some deck.js configurations, so again check out the GitHub repo for the full example.

Ember.js Views and Live Templates With Handlebars.js Part 1

| Comments

Tech-pro Ember.js Views

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’ll also give a brief background of JavaScript templating in general to provide perspective as to the problems it is solving.

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.

Read more at: http://tech.pro/tutorial/1308/emberjs-views-and-live-templates-with-handlebarsjs-part-1

Utilize Rich Input Data From W3C Pointer Events

| Comments

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.

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.

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”.

The Pointer Event Object

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:

More poiner.js
1
2
3
4
5
6
7
8
9
        var myY, myX;
        document.getElementById('myElement').addEventListener('mouseup', function(e){

            e.preventDefault();

            myY = e.offsetY;
            myX = e.offsetX;

        });

This same code will also run with Pointer Events:

More poiner.js
1
2
3
4
5
6
7
8
        document.getElementById('myElement').addEventListener('pointerup', function(e){

            e.preventDefault();

            myY = e.offsetY;
            myX = e.offsetX;

        });

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.

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

The Event Type

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:

More poiner.js
1
2
3
4
5
6
        document.getElementById('myElement').addEventListener('pointerup', function(e){

            var pointerType = e.pointerType;

        });

The type will return one of three value types:

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

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).

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:

More poiner.js
1
2
3
4
5
6
7
8
9
        document.getElementById('myElement').addEventListener('pointerup', function(e){

            var pointerType = e.pointerType;

            if (pointerType == 'touch'||4) {
                //this is a touch type pointer
            }

        });

New Values for All Pointer Types

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

PointerID: 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:

More poiner.js
1
2
3
4
5
        document.getElementById('myElement').addEventListener('pointerdown', function(e){

            var pointerId = e.pointerId
            ;
        });

isPrimary: 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:

More poiner.js
1
2
3
4
5
        document.getElementById('myElement').addEventListener('pointerup', function(e){

            var isPrimary = e.isPrimary; // will return true or false

        });

button/buttons: 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.

Figure 12-1

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.

Pen Specific Values

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.

The following values provide data in the Pointer Event Object for pens:

tiltX/tiltY: 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:

More poiner.js
1
2
3
4
5
6
7
document.getElementById('myElement').addEventListener('pointerup', function(e){


            var tiltX = e.tiltX;
            var tiltY = e. tiltY;

        });

Pressure: 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:

More poiner.js
1
2
3
4
5
6
7
document.getElementById('myElement').addEventListener('pointerup', function(e){


            var pressure = e.pressure;

        });

New Data for Touch

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:

More poiner.js
1
2
3
4
5
6
7
document.getElementById('myElement').addEventListener('pointerup', function(e){


            var width = e.width;
            var height = e.height;

        });

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

Mobile Implementations

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.

The Sample App

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.

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

Next Steps

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.

Push Notifications to the Browser With Server Sent Events

| Comments

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.

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.

What is HTTP Streaming?

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.

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.

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.

Here is a link to the companion github repository: https://github.com/html5hacks/chapter9

Ruby’s Sinatra

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.

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.

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.

For now let’s build a simple HTTP Streaming server using Sinatra.

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

Building Push Notifications

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.

A Simple HTTP Streaming Server

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

stream.rb
1
2
  require 'json'
  require 'sinatra'

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

stream.rb
1
2
  set :public_folder, Proc.new { File.join(root, "public") }
  set server: 'thin'

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: http://ruby-doc.org/stdlib-1.9.3/libdoc/erb/rdoc/ERB.html

stream.rb
1
2
3
4
5
6
7
  get '/' do
    erb :index
  end

  get '/admin' do
    erb :admin
  end

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

stream.rb
1
2
3
  def timestamp
    Time.now.strftime("%H:%M:%S")
  end

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

stream.rb
1
2
  connections = []
  notifications = []

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: http://localhost:4567/connect.

More on EventSource later.

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.

stream.rb
1
2
3
4
5
6
7
8
9
10
11
  get '/connect', provides: 'text/event-stream' do
    stream :keep_open do |out|
      connections << out

      #out.callback on stream close evt. 
      out.callback {
        #delete the connection 
        connections.delete(out)
      }
    end
  end

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

stream.rb
1
2
3
4
5
6
7
8
9
10
  post '/push' do
    puts params
    #Add the timestamp to the notification
    notification = params.merge( {'timestamp' => timestamp}).to_json

    notifications << notification

    notifications.shift if notifications.length > 10
    connections.each { |out| out << "data: #{notification}\n\n"}
  end

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:

cli
1
$ ruby stream.rb

Figure 9.15 Starting the Sinatra Server

Figure 7-2

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

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.

Set Up the HTML pages

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:

index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<html>
  <head>
    <title>HTML5 Hacks - Server Sent Events</title>
    <meta charset="utf-8" />

    <script src=”http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js”>
</script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.js"> </script>
    <script src="jquery.notify.js" type="text/javascript"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
    <link rel="stylesheet" type="text/css" href="ui.notify.css">

  </head>
  <body>
    <!—- implementation specific here -->
  </body>
</html>

The admin page will contain an input tag and a simple button.

admin.html
1
2
3
4
<div id="wrapper">
    <input type="text" id="message" placeholder="Enter Notification Here" /><br>
    <input type=”button” id="send" data-role="button">push</input>
</div>

And our receiver pages will display a simple piece of text:

receiver.html
1
2
3
<div id="wrapper">
  <p>Don't Mind me ... Just Waiting for a Push Notification from HTML5 Hacks.</p>
</div>

By launching one browser window to http://localhost:4567/admin you should now see our admin form.

Figure 9.16 The initial admin page

Figure 9-16

And, navigate to http://localhost:4567 in your browser and you should see.

Figure 9.17 The initial index page

Figure 9-17

Adding a bit of jQuery

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.

push.js
1
2
3
4
5
6
7
 $('#send').click(function(event) {
    event.preventDefault();

   var notifcation = { notifcation: $('#notification').val()};

    $.post( '/push', notifcation,'json');
 })

Now, lets open up five browser windows: one admin at http://localhost:4567/admin and four more receivers at http://localhost:4567

Figure 9.18 Opening 5 browser windows

Figure 9-18

Looking good.

But before we get started, lets set up our EventSource.

EventSource

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!

es.js
1
2
3
4
5
6
7
  var es = new EventSource('/connect');

  es.onmessage = function(e) {
    var msg = $.parseJSON(event.data);

        // … do something
  }

Now we can add a simple notification with the available data,

es.js
1
2
3
4
5
6
7
  var es = new EventSource('/connect');

  es.onmessage = function(e) {
    var msg = $.parseJSON(event.data);

// … Notify
  }

And here is the final script for the admin:

es.js
1
2
3
4
5
6
7
8
9
  $(function() {
    $('#send').click(function(event) {
      event.preventDefault();

      var notification = {message: $('#notification').val()};

      $.post( '/push', notification,'json');
    })
  });

Installing jQuery.notify

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] (https://github.com/ehynds/jquery-notify)

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

receiver.html
1
2
3
4
5
6
7
<div id="container" style="display:none">
    <div id="basic-template">
        <a class="ui-notify-cross ui-notify-close" href="#">x</a>
        <h1>#{title}</h1>
        <p>#{text}</p>
    </div>
</div>

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.

Figure 9.19 Inspecting the DOM in Chrome Dev Tools

Figure 9-19

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

es.js
1
2
3
4
$("#container").notify({
  speed: 500,
  expires: false
});

And here is the final script for the receiver:

es.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$(function() {

  $("#container").notify({
      speed: 500,
      expires: false
  });

  var es = new EventSource('/connect');
  es.onmessage = function(e) {
    var msg = $.parseJSON(event.data);
    $("#container").notify("create", {
        title: msg.timestamp,
        text: msg.notification
    });
  }
})

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

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

Figure 9.20 Pushing Notifications to the Connected Browsers

Figure 9-20

Turn Your Web App Into a Windows 8 App

| Comments

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 Visual Studio 2012 (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 here.

Figure 7-1

Once your done playing go to codeplex and download the project:

http://yetibowl.codeplex.com

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 “Blank” JavaScript App:

Figure 7-1

Next, go back to your recently downloaded code, and copy all the content from the “web” folder

Figure 7-1

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:

Figure 7-1

Before our code is going to work, we need to open up our package.appxmanifest and make one small change. Find the field for “start page” and change it to the name of your html file(game.html):

Figure 7-1

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.

Figure 7-1

Add a Little Delight for your users

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:

win8.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24




        var dataTransferManager = Windows.ApplicationModel.DataTransfer.DataTransferManager.getForCurrentView();



        dataTransferManager.addEventListener("datarequested", function (e) {
            // Code to handle event goes here.


            var request = e.request;
            request.data.properties.title = "I'm Rocking out with the Yeti";
            request.data.properties.description = "HTML share from YetiBowl Game";
            var localImage = 'ms-appx:///media/logos/yeti_logo.png';
            var htmlExample = "<p>Here's to some fun with the Yeti. If your not playing YetiBowl, then your not really having fun!</p><div><img src=\"" + localImage + "\">.</div>";

            var htmlFormat = Windows.ApplicationModel.DataTransfer.HtmlFormatHelper.createHtmlFormat(htmlExample);
            request.data.setHtmlFormat(htmlFormat);
            var streamRef = Windows.Storage.Streams.RandomAccessStreamReference.createFromUri(new Windows.Foundation.Uri(localImage));
            request.data.resourceMap[localImage] = streamRef;

        });

Figure 7-1

You can find out more about the share charm here, but we are basically taking advantage of one of the many Windows RT APIs 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.

Figure 7-1

Figure 7-1

A Few Closing Notes

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 security model that is implemented in Windows 8 Apps. Using a JavaScript library? Many libraries like YUI and jQuery already work within the Windows 8 App environment. It’s that easy, reuse your code, and your skills to build Windows 8 Store Apps.

Author: Jeff Burtoft – @boyofgreen code sample: http://touch.azurewebsites.net/yeti/game.html

Win a Free Copy of HTML5 Hacks

| Comments

Sign up on our mailing list and be put into a draw to win a free ebook:

O’Reilly Webcast: Rethinking the Possibilities of Browser-based Apps with HTML5

Wednesday, March 27, 2013 10AM PT, San Francisco | 5pm – London | 1pm – New York | Thu, Mar 28th at 4am – Sydney | Thu, Mar 28th at 2am – Tokyo | Thu, Mar 28th at 1am – Beijing | 10:30pm – Mumbai

Here is a link to the archived presentation: Watch the webcast in its original format

Presented by: Jeff Burtoft, Jesse Cravens

Duration: Approximately 60 minutes.

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.

SXSWi 2013: ‘Battle of the HTML5 Hackers’ and ‘HTML5 Hacks’ Book Signing

| Comments

We had a great turnout for the ‘Battle of the HTML5 Hackers’ presentation at SXSWi on Tuesday.

SXSWi 2013: Battle of the HTML5 Hackers - Jesse Cravens and Jeff Burtoft

Using our best CDD (Conference Driven Devlopment) techniques, we walked the audience through the creation of Nerdclustr: an HTML5 mobile Application that helps nerds find other like-minded nerds at conferences events.

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

Nerdclustr: SXSWi 2013 Ballroom G Austin Convention Center

Here is a shot of the app in action (Ballroom G in the Austin Convention Center); it performed well during the presentation. Thanks to Nodjitsu 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. Nodjitsu won out in that it actually supported the WebSokcet protocol and made deployment super simple using the jitsu CLI.

Jesse Cravens and Jeff Burtoft: SXSWi 2013 - HTML5 Hacks Book Signing

Nerdclustr source code is available here.

During the book signing, the bookstore informed us there were only 3 copies left. I’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.

The slide deck is available here:


Stay tuned for our next presentation happening online, through O’Reilly Webcasts. Join us for ‘Rethinking the Possibilities of Browser-based Apps with HTML5’ on Wednesday, March 27, 2013 10AM PT.

Build a Windows 8 App With YUI

| Comments

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.

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 directly from MSDN.

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.

What you need

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.

Step 1: add the YUI seed to your page:

win8.js
1
2
3
4


// Put the YUI seed file on your page.
<script src="http://yui.yahooapis.com/3.8.1/build/yui/yui-min.js"></script>

Step 2: start a new instance:

win8.js
1
2
3
4
5
6
7
8

<script>
// Create a YUI sandbox on your page.
YUI().use('node', 'event', function (Y) {
    // The Node and Event modules are loaded and ready to use.
    // Your code goes here!
});
</script>

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 YUI configurator. 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 from github. 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 Visual Studio Express for Windows 8. 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.

Let’s take it up a Notch

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.

Figure 7-1

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:

win8.html
1
2

<div id="contenthost" data-win-control="Application.PageControlNavigator" data-win-options="{home: '/pages/home/home.html'}"></div>

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”:

win8.js
1
2
3
4
5
6
7
8
9

WinJS.UI.processAll().then(function () {
                if (nav.location) {
                    nav.history.current.initialPlaceholder = true;
                    return nav.navigate(nav.location, nav.state);
                } else {
                    return nav.navigate(Application.navigator.home);
                }
            });

The “process all” 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.”

Figure 7-1

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.

Figure 7-1

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:

win8.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25


// For an introduction to the Page Control template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232511
(function () {
    "use strict";

    WinJS.UI.Pages.define("/pages/duck/duck.html", {
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            // TODO: Initialize the page here.
        },

        unload: function () {
            // TODO: Respond to navigations away from this page.
        },

        updateLayout: function (element, viewState, lastViewState) {
            /// <param name="element" domElement="true" />

            // TODO: Respond to changes in viewState.
        }
    });
})();

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).

Figure 7-1

This duck shooter game 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

win8.js
1
2
3
4

        ready: function (element, options) {
            // Paste Your Code right here!
        },

A Match Made in Heaven

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:

win8.js
1
2

YUI().use('transition', 'button', function (Y) {

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:

win8.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

<script type="text/javascript" src="/js/build/yui-base/yui-base.js"></script>
<script type="text/javascript" src="/js/build/oop/oop.js"></script>
<script type="text/javascript" src="/js/build/attribute-core/attribute-core.js"></script>
<script type="text/javascript" src="/js/build/classnamemanager/classnamemanager.js"></script>
<script type="text/javascript" src="/js/build/event-custom-base/event-custom-base.js"></script>
<script type="text/javascript" src="/js/build/features/features.js"></script>
<script type="text/javascript" src="/js/build/dom-core/dom-core.js"></script>
<script type="text/javascript" src="/js/build/dom-base/dom-base.js"></script>
<script type="text/javascript" src="/js/build/selector-native/selector-native.js"></script>
<script type="text/javascript" src="/js/build/selector/selector.js"></script>
<script type="text/javascript" src="/js/build/node-core/node-core.js"></script>
<script type="text/javascript" src="/js/build/node-base/node-base.js"></script>
<script type="text/javascript" src="/js/build/event-base/event-base.js"></script>
<script type="text/javascript" src="/js/build/button-core/button-core.js"></script>
<script type="text/javascript" src="/js/build/event-custom-complex/event-custom-complex.js"></script>
<script type="text/javascript" src="/js/build/attribute-observable/attribute-observable.js"></script>
<script type="text/javascript" src="/js/build/attribute-extras/attribute-extras.js"></script>
<script type="text/javascript" src="/js/build/attribute-base/attribute-base.js"></script>
<script type="text/javascript" src="/js/build/attribute-complex/attribute-complex.js"></script>
<script type="text/javascript" src="/js/build/base-core/base-core.js"></script>
<script type="text/javascript" src="/js/build/base-observable/base-observable.js"></script>
<script type="text/javascript" src="/js/build/base-base/base-base.js"></script>
<script type="text/javascript" src="/js/build/pluginhost-base/pluginhost-base.js"></script>
<script type="text/javascript" src="/js/build/pluginhost-config/pluginhost-config.js"></script>
<script type="text/javascript" src="/js/build/base-pluginhost/base-pluginhost.js"></script>
<script type="text/javascript" src="/js/build/event-synthetic/event-synthetic.js"></script>
<script type="text/javascript" src="/js/build/event-focus/event-focus.js"></script>
<script type="text/javascript" src="/js/build/dom-style/dom-style.js"></script>
<script type="text/javascript" src="/js/build/node-style/node-style.js"></script>
<script type="text/javascript" src="/js/build/widget-base/widget-base.js"></script>
<script type="text/javascript" src="/js/build/widget-base-ie/widget-base-ie.js"></script>
<script type="text/javascript" src="/js/build/widget-htmlparser/widget-htmlparser.js"></script>
<script type="text/javascript" src="/js/build/widget-skin/widget-skin.js"></script>
<script type="text/javascript" src="/js/build/event-delegate/event-delegate.js"></script>
<script type="text/javascript" src="/js/build/node-event-delegate/node-event-delegate.js"></script>
<script type="text/javascript" src="/js/build/widget-uievents/widget-uievents.js"></script>
<script type="text/javascript" src="/js/build/button/button.js"></script>
<script type="text/javascript" src="/js/build/transition/transition.js"></script>

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:

win8.js
1
2
3


WinJS.Navigation.navigate("PathToFile");

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:

win8.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25


(function () {
    "use strict";

    WinJS.UI.Pages.define("/pages/home/home.html", {
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {


            WinJS.Utilities.query("a").listen("MSPointerDown", function (evt) {
                // dont load this link in the main window
                evt.preventDefault();

                // get target element
                var link = evt.target;

                //call navigate and pass the href of the link
                WinJS.Navigation.navigate(link.href);
            });

        }
    });
})();

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:

win8.html
1
2
3


  <p><a class="duck" href="/pages/duck/duck.html" >duck</a></p>

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

Figure 7-1

Figure 7-1

Growing the App

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 “dial”. 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 YUI sample dial app:

Figure 7-1

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:

win8.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78


<!DOCTYPE HTML>
<html>
        <!-- WinJS references -->
    <link href="//Microsoft.WinJS.1.0/css/ui-light.css" rel="stylesheet" />
    <script src="//Microsoft.WinJS.1.0/js/base.js"></script>
    <script src="//Microsoft.WinJS.1.0/js/ui.js"></script>
    <!-- CSS -->
    <link rel="stylesheet" type="text/css" href="/js/build/widget-base/assets/skins/sam/widget-base.css">
    <link rel="stylesheet" type="text/css" href="/js/build/dial/assets/skins/sam/dial.css">
    <link href="dial.css" rel="stylesheet" />

    <!-- JS -->
    <script type="text/javascript" src="/js/build/yui-base/yui-base-min.js"></script>
    <script type="text/javascript" src="/js/build/intl-base/intl-base-min.js"></script>
    <script type="text/javascript" src="/js/build/oop/oop-min.js"></script>
    <script type="text/javascript" src="/js/build/event-custom-base/event-custom-base-min.js"></script>
    <script type="text/javascript" src="/js/build/event-custom-complex/event-custom-complex-min.js"></script>
    <script type="text/javascript" src="/js/build/intl/intl-min.js"></script>
    <script type="text/javascript" src="/js/build/dial/lang/dial.js"></script>
    <script type="text/javascript" src="/js/build/attribute-core/attribute-core-min.js"></script>
    <script type="text/javascript" src="/js/build/attribute-observable/attribute-observable-min.js"></script>
    <script type="text/javascript" src="/js/build/attribute-extras/attribute-extras-min.js"></script>
    <script type="text/javascript" src="/js/build/attribute-base/attribute-base-min.js"></script>
    <script type="text/javascript" src="/js/build/attribute-complex/attribute-complex-min.js"></script>
    <script type="text/javascript" src="/js/build/base-core/base-core-min.js"></script>
    <script type="text/javascript" src="/js/build/base-observable/base-observable-min.js"></script>
    <script type="text/javascript" src="/js/build/base-base/base-base-min.js"></script>
    <script type="text/javascript" src="/js/build/pluginhost-base/pluginhost-base-min.js"></script>
    <script type="text/javascript" src="/js/build/pluginhost-config/pluginhost-config-min.js"></script>
    <script type="text/javascript" src="/js/build/base-pluginhost/base-pluginhost-min.js"></script>
    <script type="text/javascript" src="/js/build/classnamemanager/classnamemanager-min.js"></script>
    <script type="text/javascript" src="/js/build/features/features-min.js"></script>

    <script src="dial.js"></script>



<body class="yui3-skin-sam"> <!-- You need this skin class -->

       <div class="dial fragment">
        <header aria-label="Header content" role="banner">
            <button class="win-backbutton" aria-label="Back" disabled type="button"></button>
            <h1 class="titlearea win-type-ellipsis">
                <span class="pagetitle">Welcome to duck</span>
            </h1>
        </header>
        <section aria-label="Main content" role="main">
            <div class="content">
<div id="example_container">
    <div id="view_frame">
        <div id="scene">
            <div id="stars"></div>
            <img id="hubble" src="/images/hubble.png"/>
            <img id="earth" src="/images/mountain_earth.png"/>
            <div class="label hubble">hubble</div>
            <div class="label thermosphere">thermosphere</div>
            <div class="label mesosphere">mesosphere</div>
            <div class="label stratosphere">stratosphere</div>
            <div class="label troposphere">troposphere</div>
            <div class="label ozone">ozone</div>
            <div class="label crust">crust</div>
            <div class="label mantle">mantle</div>
        </div>
    </div>
    <div class="controls">
        <div class="intro-sentence">From Earth to <a id="a-hubble">Hubble</a></div>
        <div id="altitude_mark"></div>
        <div id="demo"></div>
    </div>
</div>
</div>
    </section>
    </div>
</body>

</html>

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

Figure 7-1

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:

win8.html
1
2
3
4
5
6


<body class="yui3-skin-sam">
    <div id="contenthost" data-win-control="Application.PageControlNavigator" data-win-options="{home: '/pages/home/home.html'}"></div>

</body>

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

Figure 7-1

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

win8.html
1
2

<p><a href="/pages/dial/dial.html" >Dial</a></p>

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

Accessing Windows APIs with YUI

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):

Figure 7-1

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:

win8.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17


var dataTransferManager = Windows.ApplicationModel.DataTransfer.DataTransferManager.getForCurrentView();
dataTransferManager.addEventListener("datarequested", shareTextHandler);

function shareTextHandler(e) {
          var request = e.request;
          request.data.properties.title = "Share Dial Level";
          request.data.properties.description = "I'd like to share something with you";
     request.data.setText("Hello, my dial is set to " + dial.get('value') + " Kilometers in altitude");

        }

                YUI.namespace("win8App");

                YUI.win8App.sharePointer = dataTransferManager;
                YUI.win8App.shareFunction = shareTextHandler;

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.

Figure 7-1

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

Figure 7-1

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:

win8.js
1
2
3
4
5
6


unload: function () {
            // TODO: Respond to navigations away from this page.
            YUI.win8App.sharePointer.removeEventListener("datarequested", YUI.win8App.shareFunction);
        },

More information about the share contract and other Windows APIs can be found here.

Success!

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.

Conclusion

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.

Posted by: Jeff Burtoft

Build a Milestone Calendar With IndexedDB and FullCalendar.js

| Comments

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.

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.

Figure 6-8. FullCalendar.js and IndexedDB

Figure 6-8

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.

milestone form
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<form>
     <fieldset>

       <div class="control-group">
         <label class="control-label">Add a Milestone</label>
         <div class="controls">
           <h2>New Milestone</h2>
           <input type="text" name="title" value="">
           <input type="text" class="span2" name="start"
             value="07/16/12" data-date-format="mm/dd/yy" id="dp1" >
           <input type="text" class="span2" name="end"
             value="07/17/12"  data-date-format="mm/dd/yy" id="dp2" >
         </div>
       </div>

       <div class="form-actions">
          <button type="submit" class="btn btn-primary">Save</button>
          <button class="btn">Cancel</button>
       </div>

      </fieldset>
 </form>

The calendar is provided by FullCalendar.js, 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.

simple div
1
<div id='calendar'></div>

And we can’t forget to include a few dependencies:

CSS and JavaScript dependencies
1
2
3
4
5
6
<link href="../assets/css/datepicker.css" rel="stylesheet">
<link href="../assets/css/fullcalendar.css" rel="stylesheet">

<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="../assets/js/bootstrap-datepicker.js"></script>
<script src="../assets/js/fullcalendar.min.js"></script>

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).

Figure 6-9. Date pickers

Figure 6-9

To instantiate the date pickers we will include the following toward the beginning of our script:

instantiate the date pickers
1
2
3
4
$(function(){
    $('#dp1').datepicker();
    $('#dp2').datepicker();
  });

The Milestone IndexedDB

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.

namespace and normalize
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var html5hacks = {};

html5hacks.msArray = [];

var indexedDB = window.indexedDB || window.webkitIndexedDB ||
                window.mozIndexedDB;

if ('webkitIndexedDB' in window) {
  window.IDBTransaction = window.webkitIDBTransaction;
  window.IDBKeyRange = window.webkitIDBKeyRange;
}
Now we can begin to set up our database:
html5hacks.indexedDB = {};
html5hacks.indexedDB.db = null;

function init() {
  html5hacks.indexedDB.open();
}

init();

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():

open()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
html5hacks.indexedDB.open = function() {

  var request = indexedDB.open("milestones");

  request.onsuccess = function(e) {
    var v = "1";
    html5hacks.indexedDB.db = e.target.result;

    var db = html5hacks.indexedDB.db;

    if (v!= db.version) {
      var setVrequest = db.setVersion(v);
      setVrequest.onerror = html5hacks.indexedDB.onerror;

      setVrequest.onsuccess = function(e) {
        if(db.objectStoreNames.contains("milestone")) {
          db.deleteObjectStore("milestone");
        }

        var store = db.createObjectStore("milestone",
          {keyPath: "timeStamp"});

        html5hacks.indexedDB.init();
      };
    }
    else {
      html5hacks.indexedDB.init();
    }
  };
  request.onerror = html5hacks.indexedDB.onerror;
}

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.

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.

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

onsuccess()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
html5hacks.indexedDB.init = function() {

  var db = html5hacks.indexedDB.db;
  var trans = db.transaction(["milestone"], IDBTransaction.READ_WRITE);
  var store = trans.objectStore("milestone");

  var keyRange = IDBKeyRange.lowerBound(0);
  var cursorRequest = store.openCursor(keyRange);

  cursorRequest.onsuccess = function(e) {
    var result = e.target.result;

    if(!result == false){

        $('#calendar').fullCalendar({
          header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
          },
          weekmode: 'variable',
          height: 400,
          editable: true,
          events: html5hacks.msArray
        });

      return;

    }else{

      console.log("result.value" , result.value);
      buildMilestoneArray(result.value);
      result.continue();
    }
  };
  cursorRequest.onerror = html5hacks.indexedDB.onerror;
};

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.

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

buildMilestoneArray()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function buildMilestoneArray(ms) {
  html5hacks.msArray.push(ms);
}
When we reach the last record, we build the calendar by passing a configuration object to fullCalendar() and returning:
        $('#calendar').fullCalendar({
          header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
          },
          weekmode: 'variable',
          height: 400,
          editable: true,
          events: html5hacks.msArray
        });

      return;

Adding Milestones

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:

form submit
1
2
3
4
5
6
7
$('form').submit(function() {

    var data = $(this).serializeArray();

    html5hacks.indexedDB.addMilestone(data);
    return false;
  });

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

Figure 6-10. Viewing milestone objects in the Chrome Inspector

Figure 6-10

Let’s take a closer look at our addMilestone method:

addMilestone()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
html5hacks.indexedDB.addMilestone = function(d) {
  var db = html5hacks.indexedDB.db;
  var trans = db.transaction(["milestone"], IDBTransaction.READ_WRITE);
  var store = trans.objectStore("milestone");

  var data = {
    "title": d[0].value,
    "start": d[1].value,
    "end": d[2].value,
    "timeStamp": new Date().getTime()
  };

  var request = store.put(data);

  var dataArr = [data]
  request.onsuccess = function(e) {
    $('#calendar').fullCalendar('addEventSource', dataArr);
  };

  request.onerror = function(e) {
    console.log("Error Adding: ", e);
  };
};

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.

Make Your Web App Respond to Device Orientation Changes

| Comments

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.

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.

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).

Figure 2-16

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

Here is the markup that makes each view work:

orientation.html
1
2
3
4
5
<div class="row">
  <div class="span4">...</div>
  <div class="span4">...</div>
  <div class="span4">...</div>
</div>

Here is the CSS for the three-column view:

orientation.css
1
2
3
.row {
   width: 100%;
}

Figure 2-17

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

orientation.css
1
2
3
4
5
.span4 {
   width: 300px;
   float: left;
   margin-left: 30px;
}

and the CSS for the single-column view:

orientation.css
1
2
3
4
5
6
7
8
.row {
   width: 100%;
}
.span4 {
   width: auto;
   float: none;
   margin: 0;
}

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:

orientation.css
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@media screen and (orientation:landscape) {
.row {
   width: 100%;
}
.span4 {
   width: 300px;
   float: left;
   margin-left: 30px;
}
}
@media screen and (orientation:portrait) {
.row {
   width: 100%;
}
.span4 {
   width: auto;
   float: none;
   margin: 0;
}
}

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.

Why Not Width?

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.

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.

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.

Want to try it out? View this code sample in our GitHub Repo.