HTML5 Hacks

Hacking Next Generation Web Technologies

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.

Elegantly Resize Your Page With the @-viewport CSS Declaration

| Comments

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.

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:

meta.html
1
<meta name="viewport" content="width=320" />

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.

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

CSS Pixels

To follow what’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 this post about viewports. Here’s the summary:

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

Let’s look at an example:

Figure 7-1

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

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.

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.

@-viewport CSS

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.

The specification can be found here: http://dev.w3.org/csswg/css-device-adapt/

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:

viewport.css
1
2
3
@-viewport {
width: 640px;
}

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.

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:

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

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

viewport.css
1
2
3
4
5
@media (max-width: 699px) and (min-width: 520px) {
  @-viewport {
    width: 640px;
  }
}

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.

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:

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

Zoom can be used by itself or in conjunction with a width or height value:

viewport.css
1
2
3
4
@-viewport {
    width: device-width;
    zoom: .5;
  }

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:

  • auto: let the user agent determin
  • landscape: lock the device in landscape orientation
  • portrait: lock the device in portrait mode

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

viewport.css
1
2
3
4
5
6
@viewport {
    width: 980px;
    min-zoom: 0.25;
    max-zoom: 5;
    orientation: landscape;
}

Internet Explorer Implementation

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:

viewport.css
1
2
3
@-ms-viewport {
  width: device-width
}

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.

Legacy Implementations

When most developers think about viewport, this is what they think of:

meta.html
1
<meta name="viewport" content="width=320" />

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.

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.

Internet explorer

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:

meta.html
1
<meta name="viewport" content="width=480" />

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:

meta.html
1
<meta name="viewport" content="width=device-width" />

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.

Safari

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:

meta.html
1
<meta name="viewport" content="width=device-width" />

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.

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.

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.

Make Your Page Consumable by Robots and Humans Alike With Microdata

| Comments

HTML5 microdata provides the mechanism for easily allowing machines to consume the data on your pages, while not affecting the experience for the user.

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.

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.

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:

scope.html
1
2
3
4
5
6
7
8
9
<div itemscope>
    <span itemprop="name">Fred</span>
</div>
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:
<div itemscope>
    Hello, my name is <span itemprop="name">Fred</span>.
    I was born on
   <time itemprop="birthday" datetime="1975-09-29">Sept. 29, 1975</time>.
</div>

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

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:

scopeitem.html
1
2
3
4
5
6
7
<li itemscope>
    <ul>
        <li>Name: <span itemprop="name">Fred</span></li>
        <li>Phone: <span itemprop="telephone">210-555-5555</span></li>
        <li>Email: <span itemprop="email">thebuffalo@rockandstone.com</span></li>
    </ul>
</li>

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:

json.js
1
2
3
4
    Item: {    name: 'Fred',
        telephone: '210-555-5555',
        email: 'thebuffalo@rockandstone.com'
        }

Now let’s build ourselves a whole list:

wholelist.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
<ul>
<li itemscope>
    <ul>
        <li>Name: <span itemprop="name">Fred</span></li>
        <li>Phone: <span itemprop="telephone">210-555-5555</span></li>
        <li>Email: <span itemprop="email">thebuffalo@rockandstone.com</span></li>
    </ul>
</li>
<li itemscope>
    <ul>
        <li>Name: <span itemprop="name">Wilma</span></li>
        <li>Phone: <span itemprop="telephone">210-555-7777</span></li>
        <li>Email: <span itemprop="email">thewife@rockandstone.com</span></li>
    </ul>
</li>
<li itemscope>
    <ul>
        <li>Name: <span itemprop="name">Betty</span></li>
        <li>Phone: <span itemprop="telephone">210-555-8888</span></li>
        <li>Email: <span itemprop="email">theneighbour@rockandstone.com</span></li>
    </ul>
</li>
<li itemscope>
    <ul>
        <li>Name: <span itemprop="name">Barny</span></li>
        <li>Phone: <span itemprop="telephone">210-555-0000</span></li>
        <li>Email: <span itemprop="email">thebestfriend@rockandstone.com</span></li>
    </ul>
</li>
</ul>

To our human friends the page looks something like Figure 1-14.

Figure 1-14

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

To our machine friends, the code looks something like this:

itemjson.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    Item: {    name: 'Fred',
        telephone: '210-555-5555',
        email: 'thebuffalo@rockandstone.com'
        },
    Item: {    name: 'Wilma',
        telephone: '210-555-7777',
        email: 'thewife@rockandstone.com'
        },
    Item: {    name: 'Betty',
        telephone: '210-555-8888',
        email: 'theneighbor@rockandstone.com'
        },
    Item: {    name: 'Barny,
        telephone: '210-555-0000',
        email: 'thebestfriend@rockandstone.com'
        }

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

Details, Details!

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:

getitem.js
1
document.getItems();

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 http://example.com/feline, our cat markup would look something like this:

More lastscope.html
1
2
3
4
5
6
7
<li itemscope itemtype="http://example.com/feline">
    <ul>
        <li>Name: <span itemprop="name">Dino</span></li>
        <li>Phone: <span itemprop="telephone">210-555-4444</span></li>
        <li>Email: <span itemprop="email">thecat@rockandstone.com</span></li>
    </ul>
</li>

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

getsample.js
1
document.getItems("http://example.com/feline")

Thanks to this simple API, your microdata-enriched markup is both easy to produce and easy to consume.

Configure Amazon S3 for Cross Origin Resourse Sharing to Host a Web Font

| Comments

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.

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.

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

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.

What Is an Amazon S3 Bucket?

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.

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.

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.

Figure 9-21. S3 Management Console

Figure 9-21

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

Figure 9-22. Creating an S3 bucket in the S3 Management Console

Figure 9-22

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.

Figure 9-23. Naming an S3 bucket in the S3 Management Console

Figure 9-23

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

Figure 9-24. The html5hacks S3 bucket

Figure 9-24

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

Same Origin Policy

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:

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

1 http://en.wikipedia.org/wiki/Same_origin_policy

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.

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.

Using Web Fonts in Your Application

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.

Each of these techniques has limitations.

  • When calling the @font-face service you are limited to the fonts within the particular service’s database.
  • 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.
  • 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.
  • Converting the font to Base64 adds additional weight to the stylesheet, and does not take advantage of caching.

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 http://www.dafont.com.

Uploading Your Font to Your Amazon S3 Bucket

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

Figure 9-25. An uploaded BebasNeue font

Figure 9-25

Adding the Web Font to Your Web Page

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

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

geo.html
1
2
3
4
5
6
7
8
9
10
<html>
  <head>
    <title>S3 - font</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" type="text/css" href="styles.css">
  </head>
  <body>
    <h1 class="test">HTML5 Hacks</>
  </body>
</html>

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.

style.css
1
2
3
4
5
6
7
8
@font-face {
  font-family: BebasNeue;
  src: url('https://s3.amazonaws.com/html5hacks/BebasNeue.otf');
}

.test {
  font-family: 'BebasNeue';
}

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.

Figure 9-26. Opera browser showing the BebasNeue font

Figure 9-26

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

Figure 9-27. Firefox browser failing to show the BebasNeue font

Figure 9-27

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

Figure 9-28. Firefox browser showing an empty response

Figure 9-28

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.

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

What Is CORS?

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.

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.

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.

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

Let’s get started.

Configuring CORS at Amazon S3

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

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.

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.

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

config.xml
1
2
3
4
5
6
<CORSConfiguration>
<CORSRule>
<AllowedOrigin>*/AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
</CORSRule>
</CORSConfiguration>

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

Figure 9-29. Configuring CORS in the S3 Management Console

Figure 9-29

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.

Figure 9-30. Firefox browser successfully showing the BebasNeue font

Figure 9-30

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.