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.
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.
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
12345
<audiocontrolsid="myPlayer"><sourcesrc="myAudio.m4a"type="audio/mp4"/><sourcesrc="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:
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
123456789
console.log(audioPlayer.currentTime);// returns 0 since we haven't started playing the audio yetaudioPlayer.currentTime=10;// move to 10 seconds into the audioconsole.log(audioPlayer.currentTime);// returns 10audioPlayer.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.
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:
// create an array for our segment timestamps varsegments=[];// create a placeholder for our audio element reference varaudio;// we'll get to this variable latervarsegmentEnd=0;functioninit(){// get the audio element we added to our pageaudio=document.getElementById('audioNarration');// use deck.js built-in functionality to get all slides and current slidevar$slides=$.deck('getSlides');var$currentSlide=$.deck('getSlide');// set initial values for time position and indexvarposition=0;varcurrentIndex=0;// now loop through each slide$.each($slides,function(i,$el){// get the duration specified from the HTML elementvarduration=$el.data('narrator-duration');// this determines which slide the viewer loaded the page onif($currentSlide==$el){currentIndex=i;}// push the start time (previous position) and end time (position + duration) to an array of slidessegments.push([position,position+duration]);// increment the position to the start of the next slideposition+=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
12345678910
functionchangeSlides(e,from,to){// check to make sure audio element has been foundif(audio){// move the playback to our slides startaudio.currentTime=segments[to][0];// define the end of our sectionsegmentEnd=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:
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:
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.
And then add our event listeners in the deck.init callback:
deck.narrator.js
123456789
$d.bind('deck.init',function(){// ... other code here ...// Sync audio with slidesaudio.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.
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.
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:
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:
-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
123456789
document.getElementById('myElement').addEventListener('pointerup',function(e){varpointerType=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:
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
12345
document.getElementById('myElement').addEventListener('pointerup',function(e){varisPrimary=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.
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:
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:
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:
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.
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.
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.
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
12
require'json'require'sinatra'
Then, we set up a public folder, and set the server to use the evented ruby 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
1234567
get'/'doerb:indexendget'/admin'doerb:adminend
We’d like to timestamp each notification, so here is a very simple function definition.
stream.rb
123
deftimestampTime.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
12
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
1234567891011
get'/connect',provides:'text/event-stream'dostream:keep_opendo|out|connections<<out#out.callback on stream close evt. out.callback{#delete the connection connections.delete(out)}endend
Finally, any data this posted to the /push route is pushed out to each connected device.
stream.rb
12345678910
post'/push'doputsparams#Add the timestamp to the notificationnotification=params.merge({'timestamp'=>timestamp}).to_jsonnotifications<<notificationnotifications.shiftifnotifications.length>10connections.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
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
1234567891011121314151617
<html><head><title>HTML5 Hacks - Server Sent Events</title><metacharset="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><linkrel="stylesheet"type="text/css"href="style.css"><linkrel="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.
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.
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
1234567
vares=newEventSource('/connect');es.onmessage=function(e){varmsg=$.parseJSON(event.data);// … do something}
Now we can add a simple notification with the available data,
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.
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
In order for jQuery.notify to initialize, you must first call the following:
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.
Once your done playing go to codeplex and download the project:
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:
Next, go back to your recently downloaded code, and copy all the content from the “web” folder
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:
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):
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.
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
123456789101112131415161718192021222324
vardataTransferManager=Windows.ApplicationModel.DataTransfer.DataTransferManager.getForCurrentView();dataTransferManager.addEventListener("datarequested",function(e){// Code to handle event goes here.varrequest=e.request;request.data.properties.title="I'm Rocking out with the Yeti";request.data.properties.description="HTML share from YetiBowl Game";varlocalImage='ms-appx:///media/logos/yeti_logo.png';varhtmlExample="<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>";varhtmlFormat=Windows.ApplicationModel.DataTransfer.HtmlFormatHelper.createHtmlFormat(htmlExample);request.data.setHtmlFormat(htmlFormat);varstreamRef=Windows.Storage.Streams.RandomAccessStreamReference.createFromUri(newWindows.Foundation.Uri(localImage));request.data.resourceMap[localImage]=streamRef;});
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.
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.
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
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.
We had a great turnout for the ‘Battle of the HTML5 Hackers’ presentation at SXSWi on Tuesday.
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.
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.
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.
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
1234
// Put the YUI seed file on your page.<scriptsrc="http://yui.yahooapis.com/3.8.1/build/yui/yui-min.js"></script>
Step 2: start a new instance:
win8.js
12345678
<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.
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:
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”:
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.”
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.
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
12345678910111213141516171819202122232425
// 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).
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
1234
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
12
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:
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
123
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
12345678910111213141516171819202122232425
(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 windowevt.preventDefault();// get target elementvarlink=evt.target;//call navigate and pass the href of the linkWinJS.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:
Our app now navigates from the start page to the duck sample, and back again.
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:
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:
<!DOCTYPE HTML><html><!-- WinJS references --><linkhref="//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 --><linkrel="stylesheet"type="text/css"href="/js/build/widget-base/assets/skins/sam/widget-base.css"><linkrel="stylesheet"type="text/css"href="/js/build/dial/assets/skins/sam/dial.css"><linkhref="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><bodyclass="yui3-skin-sam"><!-- You need this skin class --><divclass="dial fragment"><headeraria-label="Header content"role="banner"><buttonclass="win-backbutton"aria-label="Back"disabledtype="button"></button><h1class="titlearea win-type-ellipsis"><spanclass="pagetitle">Welcome to duck</span></h1></header><sectionaria-label="Main content"role="main"><divclass="content"><divid="example_container"><divid="view_frame"><divid="scene"><divid="stars"></div><imgid="hubble"src="/images/hubble.png"/><imgid="earth"src="/images/mountain_earth.png"/><divclass="label hubble">hubble</div><divclass="label thermosphere">thermosphere</div><divclass="label mesosphere">mesosphere</div><divclass="label stratosphere">stratosphere</div><divclass="label troposphere">troposphere</div><divclass="label ozone">ozone</div><divclass="label crust">crust</div><divclass="label mantle">mantle</div></div></div><divclass="controls"><divclass="intro-sentence">From Earth to <aid="a-hubble">Hubble</a></div><divid="altitude_mark"></div><divid="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:
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:
When we reload our application with the new app, we have a skinned version of out dial:
Now we’re all set to go. Let’s go back to home.html and add a link to our new page:
win8.html
12
<p><ahref="/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):
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
1234567891011121314151617
vardataTransferManager=Windows.ApplicationModel.DataTransfer.DataTransferManager.getForCurrentView();dataTransferManager.addEventListener("datarequested",shareTextHandler);functionshareTextHandler(e){varrequest=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.
I’ll select the mail app and you can see how this data will be shared:
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
123456
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.
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
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.
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:
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
To instantiate the date pickers we will include the following toward the beginning of our script:
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
1234567891011121314151617181920
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():
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.
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()
1234567891011121314151617
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
1234567
$('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
Let’s take a closer look at our addMilestone method:
addMilestone()
1234567891011121314151617181920212223
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.
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:Our sample page in landscape mode on an iPad, with three columns of content
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:
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.