In the first part of this epic and questionably long series, I did a very quick introduction to the ChildBrowser plugin for PhoneGap. In this post, i’m going to expand the application I built in the first post to leverage the deep Twitter integration in iOS 5.
You may come to a point in your application when you want to allow people to share what they have found or created via your application, with the rest of the internet via Twitter. There are a variety of ways to accomplish this.
You could roll your own where you authenticate the user to Twitter via their OAuth mechanism. If you like that sort of pain, this can work just fine. However, you have fringe issues that you will have to address immediately, which include shortening links and the nightmare that is trying to share images by uploading them to Twitter’s sharing service.
Someone once Tweeted that sharing on the internet is in fact broken, because OAuth makes it so darn painful. Oh wait, that was me.

In the case of my application, I could rely on the pages that I link to having share buttons, but then you have to navigate the page, click on the tiny twitter button and sign in if you haven’t already signed in on your phone since the last time you cleared the cache. That’s a terrible user experience though. Case in point below…

Note that this is not a problem with the author’s site, its simply a usability issue that mobile doesn’t handle very well. The button is tiny and when you click on it, you are redirected to yet another window to post to Twitter. On the web, this is fine. On a phone, not so much.
What you may or may not know, is that iOS has deep integration with Twitter. It’s actually built right into the OS and will take care of shortening links, uploading images - the whole 9. But as with many PhoneGap situations, there is no way to use this with PhoneGap out of the box.
Luckily for us, Randy McMillan has built a nifty plugin for PhoneGap that allows us to take advantage of the native Twitter sharing and it’s darn easy.
As with most PhoneGap plugins, the trickiest part about the plugin is getting it installed correctly and running. Once you do that, the API is dead simple and Randy has done a great job of making sure that all scenarios are covered. Let’s take a look at how to use the Twitter Plugin for PhoneGap.
Download the PhoneGap Plugins if you haven’t already.
Inside the iOS folder, you will find the Twitter Plugin. I’m simply going to extend the Reddit Browser Application that I built in the ChildBrowser Plugin post to allow users to tweet a Reddit story directly from the application using the really nice Twitter integration in iOS 5.
Inside the Twitter folder, you will find an native folder in which you will see a native folder. This is the folder that you want to add to your project.
Right-click the plugins folder in your project and select Add Files. Browse to that ios folder and select it. Remember to choose “Add groups for any added folders”. This will create a yellow folder under plugins. If it creates a blue one, you did it wrong. Delete them and do it again.

Add the entry to your Cordova.plist file. The entry key is com.phonegap.twitter and TwitterPlugin for the value.

We are going to need to add Account and Twitter references to our build phases. To do that, select your project name, in the side bar that appears next to it select Targets and your project name. Then select the Build Phases tab and add Twitter and Accounts to the Link Binary With Libraries section.

Add the TwitterPlugin.js file to your www folder and don’t forget to add the reference to your index.html.
If you get some errors when running your project, check the weak linking issue at the bottom of the plugin GitHub page. I had to make this change to my project in order to get the plugin to work.
Now I can tweet one of the Reddit stories simply by calling the plugin and the composeTweet method.
The method takes 4 parameters.
In this case, I am just passing the title of the story along with the URL.
$("#popular_news").on("click", ".tweet-button", function(e) {
var title = $(e.currentTarget).data("title"),
url = $(e.currentTarget).data("url")
window.plugins.twitter.composeTweet(
null,
function(e) {
if ($(e).trim().toLower() !== "canceled") {
navigator.notify.alert("Failed sending Tweet..." + e);
}
},
title, {
urlAttach: url
}
);
});
I’m not doing anything in the above success function so I just pass null. But the failure function is necessary in case the user tries to Tweet without a connection. This function returns a string error. It returns Canceled if the user simply cancels out of the dialog. In that case, we don’t want to pop up a notification. Only in actual failures do we want to show something.

But there is one thing here that we are assuming, and that is the fact that the user has iOS 5 which supports Twitter integration their Twitter account linked to their phone. Like I said, Randy thought things through so we have some functions to check for that.
In the case that they are not on iOS 5, I’m going to hide the tweet button via a boolean value. In the case that they have Twitter integration, but they have not linked their account, I’m going to prompt them to go do that.

$("#popular_news").on("click", ".tweet-button", function(e) {
var title = $(e.currentTarget).data("title"),
url = $(e.currentTarget).data("url")
// is twitter setup? If not, tell the user to go do it
window.plugins.twitter.isTwitterSetup(function(r) {
if (r === 1) {
// twitter is setup, compose a new tweet
window.plugins.twitter.composeTweet(
null,
function(e) {
if ($(e).trim().toLower() !== "canceled") {
alert("Failed sending Tweet..." + e);
}
},
title, {
urlAttach: url
}
);
}
else {
navigator.notification.alert("Please setup Twitter under Settings to use this feature",
null, "No Twitter :("); }
});
e.preventDefault();
});
And here is a short video demonstrating the Twitter Plugin leveraging the Twitter Integration is iOS 5.
I hope this rundown on the Twitter Plugin has been useful for you. This plugin does more than just tweet, including getting Timeline and Mentions. As always, you can grab the source code off of my GitHub repository.
This is the first post in a series that I have been meaning to write for a while. PhoneGap (now called Cordova) is the defacto platform for building native applications with HTML5. In the past few years we have seen quite a few JavaScript frameworks pop up to help you with your UI, which has always been the toughest part.
To name a few we have…
…and several more.
We’ve just about got this nut cracked. PhoneGap provides a fantastic wrapper for deploying your applications and taking advantage of native device features.
But there are places where we still have a gap. Fortunately enough, there is a GitHub Repo dedicated to bridging this gap with plugins for PhoneGap that provide missing or extended functionality to the base PhoneGap install.
In this post, we’ll take a look at one of these plugins called The ChildBrowser Plugin. I’ll go over the (Why, What, Where, How) WWWH for each of these plugins.
All of my demos will be done in iOS. Note that the process for doing this on Android may be different than what you see here.
PhoneGap wraps your application in a mobile Safari window. But what if you want to open a new window? While we are doing HTML/JavaScript development in PhoneGap, some things do not work. For instance, you cannot simply call…
window.open("http://google.com")
or
<a href="http://www.reddit.com">View On Reddit</a>
Spawning new windows or redirecting to other content is not OK and doesn’t work they way it does on the web. The reasons for spawning a new window in a web application vary, but consider the following scenarios…
The Child Browser Plugin was created just for this scenario. It allows you to open a new window and even has events to capture responses from the spawned child window.
The ChildBrowser is part of the PhoneGap Plugins Project.
Once you download it, you need to install it. I’m going to create a sample application that lets you pull in Reddit Stories and then click on a link to view the article full screen in the child browser window if you so choose to do so.
In my first pass at this, I create a link for each item with the href set to the url of the article.

What happens when I click on the link?

Hmmmm, thats weird. It took us to the right web page and we didn’t leave the application, but now my application is gone and we have a website instead with no back button. Not what we wanted.
Let’s try it again and set the target of the href to _blank.

That works too, but it opened up mobile Safari and my app went away. It’s going to be a pain for users to click on links, go to Safari, come back to my app and then repeat over and over again. We need a way to let them browse web content without leaving our app.
We’ve seen enough of the What and Why, let’s look at the How.
The first step is of course to download the ChildBrowser plugin. You can download the whole repo of plugins, which contains a version for every platform. As I mentioned earlier, I am going to be targeting iOS.
It’s important to mention here that if you haven’t downloaded PhoneGap (Cordova) recently, you need to do it again. It recently switched to being called Cordova and all the namespaces changed. The plugins will throw errors if you don’t have Cordova.
For my UI, I am using the new Kendo UI Mobile.
Once you have downloaded the plugins, browse to the iOS directory and then to the ChildBrowser folder. Inside that folder, drag ChildBrowser.js or ChildBrowser.min.js to the www folder of your application. You can delete the FBConnect example.
Now in XCode, right click on the Plugins folder and select Add Files. Browse to the ChildBrowser folder and select it. When you click Add, make sure you have the Create folder references for any added folders selected. You also want the Destination checkbox checked, but it should be by default.

Now we need to tell PhoneGap (Cordova) about this new plugin by opening up the Cordova.plist file and making an entry in the plugins section. The correct key/value pair entry is ChildBrowserCommand on both sides.

Add a script reference for the ChildBrowser.js or ChildBrowser.min.js to your index.html file in the www folder.
<script src="ChildBrowser.js"></script>
Once the script reference has been added, I can call the ChildBrowser plugin from JavaScript. The following function will be called when an item is clicked. It open a child window and sets the url of the window. Notice that we have to install the plugin first and make sure it is in fact installed before trying to use it.
pub.goToUrl = function(sender) {
// get url off of data attribute from item that was clicked
var url = $(sender).data("url");
// install ChildBrowser
var cb = ChildBrowser.install();
// if ChildBrowser is installed, open it with target set
if(cb != null)
window.plugins.childBrowser.showWebPage(url);
}
Now when I click on an item, a nifty window slides up from the bottom. It allows the user to fully navigate web content, and when they are done, it simply slides down and goes away, bringing them right back to my application. Check out the short YouTube video below showcasing the ChildBrowser in action.
The ChildBrowser plugin is a very nice way to display external content or allow your users to read PDF files without them ever having to leave you application. This is a much better experience for the user.
PhoneGap (Cordova) is really great, but you have to know how to bridge the gaps in functionality when they exist.
You can grab the Xcode project used here on my GitHub page. I’ll keep this repo updated with this series of posts, providing the demo projects that I built here. Hop on over and grab the download.
Start developing with PhoneGap. It’s easy, and it’s getting better all the time. There are gaps, but we can bridge those with plugins providing an end to end native experience with HTML5.
I’ve been following along with Jeffrey Way (who has a smokin’ hot wife - his words) and his 30 Days To Learn jQuery over on Tuts+. I can’t say enough about this series.
It’s. So. Good.
His understanding of not just jQuery, but JavaScript in general and the ability to create relevant demos and examples is unmatched.
OK. Enough about Jeffrey. I don’t get paid to talk about Tuts+. But maybe I should… Hit me up Jeff.
He did something in a recent episode that made me go. “WAIT! WHAT!?! You can do that?”. Touch slider to rewind on iPad. Touch slider…touch slider….Finally - rewind and watch again. Why is it so hard to grab the video scrubber on iOS sometimes?
He showed JavaScript Array Notation. This also commonly referred to as “Square Bracket Notation”. Now this was something that I sort of *knew* about in the back of my mind, but it never clicked really. I never used it.
The concept is simple. You have a JavaScript object. That object has methods. You already know that you can call these methods with the dot notation.
object.method();
Let’s look at a simple demo. In this example I have created an object called Lassie. Lassie has some methods that she can execute. Instead of just logging an event, I used pictures I stole off the internet. Because it’s more fun.
In this rather bad example, I have two buttons. Each time a button is clicked, I can fire a method on the lassie object. Try it out.
That works, but we have 4 methods and we would need a button for each method. It would be better to have a drop down of available actions and then execute the right method based on the selection.
What you might not realize is that JavaScript also allows you to call a method with Array Notation. So instead of calling this…
lassie.bark();
You can call this…
lassie[“bark”]();
Did you catch that? All you need is the string representation of the method name. We could now refactor the above example to use a drop down list instead and then just use the value of the selected option to execute the right method. Dynamically.
Lets look at another less ridiculous example of array notation.
I’ve been working on an HTML5 application called HTML5 Camera. This site uses bleeding edge WebRTC to capture video from your webcam and play it back through an HTML5 video tag. It then captures the video output to a canvas element. Once the image is on the canvas, I can manipulate the pixels to apply effects to the image.
I’m currently using a forked version of VintageJS from Robert Fleischman. It allows you to apply vintage effects to an image with JavaScript.
In my version, each time I call the vintage() method on an image, I have to pass in an object which contains configuration values. For instance, the standard vintage object looks like this…
Each of the effects presets look like this. I have a JavaScript file that is full of these presets. Now in my case, I will eventually be loading these effects objects from a remote URL and serializing them into JSON objects so my implementation will change slightly. Well, probably a lot.
I need to call the vintage() method on the image and pass in the object containing the presets. Normally, if I knew what preset to pass, I would just pass it.
$(“img”).vintage(effects.presets.default);
What I needed to do was have a drop down list that would display each of the effects dynamically as I add them and put them in a drop down list. I could do that easy enough with a for loop and hasOwnProperty.
Then I can apply the effect by selecting the image, calling the .vintage() method (which is part of the VintageJS jQuery plugin) and passing in an effects object based on the value of the drop down list.
What follows is a working example. You can set the effect on the image of me “raising the roof” by changing the drop down value. There is no list of effects anywhere. This drop down is populated directly off of the effects object and then the effect is applied using JavaScrpt array notation passing in the string value of the selected drop down list item.
And this is the code that both populates the drop down and executes retrieves the appropriate object for based on the user’s selection in the drop down.
So in this last example, I wasn’t calling a method - but rather retrieving an object based on it’s “string” representation.
If you have worked with static languages before, you know that in order to do something like this (pre-dynamics in .NET 4.0 and things like that), you had to use Reflection. And it was not fun. Kind of like the flu is not fun.
There is so much power in dynamic languages. With JavaScript Array Notation, you can execute arbitrary methods or retrieve objects inside of other objects without having anything more than the string representation of the object/method name. And that, is sexy.
Let’s talk about Private Browsing mode.
You know what it is. It has other names that are less savory as it is generally agreed upon that browsing privately is because you don’t want other people to know what you are looking at. It’s commonly called “Porn Mode”. Well, so much for staying classy.
But we’re all adults here. We can get through this. Stop the giggling.
Mozilla has offered some very eye opening metrics on this subject, including the fact that Private Browsing mode is used usually in a window of 10 minutes or less. Here is a chart offered by Mozilla from their metrics blog on the issue.

Source: Blog Of Metrics - Understanding Private Browsing.
Care to see some more metrics?
None of it is really that surprising. I found myself in an odd conversation at dinner lately about Chrome’s Incognito Mode (FireFox calls it Private Browsing). We all had a good laugh, but I thought about all the legitimate uses that Private Browsing has. Besides buying gifts for your wife.
Shockingly, it is an essential tool in every day web use when you find out what it can do for you. I even polled some other people on this and found that it has quite a few legitimate uses. Here are some of the ones I use myself along with ones that were recommended to me.
So fire up your favorite browser and let’s make a Private Browsing an honest citizen. I will be using Chrome for these examples. On a Mac, that’s cmd + shift + n.
What is one of the single most annoying things about Chrome when you are doing web development? Caching. Chrome will cache certain files, especially if you’re using external templates in JavaScript and loading them in. It persists the cache across window instances as well. Closing the browser and re-opening does not help.

Uhhhh. That’s so annoying.
When you refresh in Private Browsing mode, it won’t read from the cache. Well, that’s partially true. I’ve seen it read from the cache on the initial load in a new tab but not when the tab is refreshed. So just watch the network activity to make sure that you have a fresh copy of your files.
Ralph Whitbeck pointed out to me that it’s super useful for multiple Gmail accounts. Beyond that, it’s super useful for Google accounts in general. Say you are logged into Gmail in one tab and you want to log in on another tab on a different account. Once you log yourself out in the second tab, it logs you out in the first as well.
This actually happens in Chrome Incognito Mode as well. The trick is to keep one account open in regular browsing mode and the second in Incognito mode. Now you could log in to your Gmail account and a seperate - perhaps “company” - YouTube account at the same time without stepping on yourself.
And guess where else this works….
FACEBOOK!
Yes - that’s right. Once called the “The Birthday Website” by Scott Hanselman, the prolific social network for sharing what you are cooking for dinner and giving people completely disingenuous birthday wishes is a great candidate for multiple accounts.

Scenario: You are a lover scorned. You need to have your regular account open so you can stay up to date on the lives of a bunch of people you hated in high school, but you also need one for your fake account so you can stalk your ex and find out who they are seeing now. You need to be able to do both so you can launch your break with reality at just the right time.
As a point of fact, I have my facebook and my wife’s open right now. Wait, she’s listed as single?!? Hold on. I’ll be right back.
……………………………………
Ok, back. In other news I’m now single.
Menno Van Slooten noticed that it’s also great for going down viral rabbit holes. You know, someone sends you a video of a large person falling down and you click on all the other videos of large people falling down. 4 hours and 300 memes later your internet history is shot to hell and you cannot find that article you were reading the other day about legitimate uses of private browsing mode.

Since private browsing does not store your history, it won’t polute your main timeline. Don’t just randomly browse the web in a normal window or your history gets pretty useless pretty fast.
From helping you with development to allowing you to unleash your inner psycho on Facebook, it’s great to remember that private browsing mode is good for more than just your sultry late night browsing. Although its really good for that too.
I did a tounge-in-cheek video response to Web Bos this week who sumbitted this epic video for FluentConf showcasing his all around HTML5 video awesomeness. In this video he streams directly to his browser and applies effects on the fly from the console. If this doesn’t impress you, you may be heavily medicated.
Uh - yeah. Like A Boss. Or rather like a Bos.
Now I saw this and had 2 thoughts…
1. That’s awesome. My video now sucks.
2. How the heck did he do that?
In the name of education and also to increase my own chances of getting picked up for FluentConf, I made an HTML5 video video of my own. Video video.
My video wasn’t nearly as good, but I really enjoyed working with the new methods for capturing native video with nothing but a browser. No plugins, just Chrome and JavaScript.
First lets do a little primer on WebRTC. This is a project that was open sourced by Google last year in an attempt to enable Real Time Communication within a browser, handled natively by the browser. Hence the RTC name.
Apparently, WebRTC has been around for a while and according to the WebRTC site is:
“Already integrated with best-of-breed voice and video engines that have been deployed on millions of end points over the last 8+ years.”.
- http://www.webrtc.org/faq#TOC-What-is-WebRTC-
It appears that now Google is attempting to make this the defacto standard for real time communication in the browser.
WebRTC provides a layer of abstraction which allows developers to use whichever supported “signaling” protocol they wish. Additionally WebRTC has a broad range of codecs for audio and video as well as networking support for buffering and to prevent against packet loss.
There’s a whole site dedicated just to WebRTC and I encourage you too read up on it here. Especially if you are having trouble sleeping.
WebRTC is currently supported in the dev branch of Chrome along with Canary - which you can think of as the bleeding edge of Chrome. I use the stable branch of Chrome along with Canary for one main reason. You can run Canary side-by-side with your existing stable Chrome install without any adverse affects. They use different profiles.

Once you have downloaded either the dev or Canary builds, you have to enable WebRTC. There are two ways to do this. The documentation says to enable it by launching it with the “—enable-media-stream” switch. This is to complicated for me, so intead just launch Chrome and go to chrome://flags. That will take you to a GUI page where you can scroll down an enable WebRTC support.

Who gives you amazing screenshots with unnecessary arrows? It’s just what I believe in.
Streaming the video to your browser is dead simple. First you have to have a webcam for obvious reasons.
Start with a simple HTML5 video tag in your page. Remember, if the video tag is not supported by the browser, you will see the text in between the open and close video tags.
It’s time to drop down into the JavaScript and fire up the webcam.
The method we are going to be looking at is found off the navigator object which comes along for the ride with a supported browser. The function we will call is webkitGetUserMedia(). This is incredibly Chrome specific at the moment, but it’s the bleeding edge of HTML5.
This method takes in 3 arguments. The first is a string denoting the type of media we are going to get - in this case “video”. The second is the callback for when the stream is acquired and the third is a function that executes if there is an error while getting the stream.
Note that the error function does not work if WebRTC is not supported. If the browser doesn’t support it, it dies silently but you can see it under the covers in your dev tools.

Assuming that your browser supports WebRTC and you got the stream, you enter the callback for success. The success callback is where you need to select the video tag on your page and assign it the stream from the navigator.
The complete code for a page that displays your beautiful face via the webcam looks like this…
That’s pretty darn simple code for what you get. Now the cool thing is that this video is an HTML DOM object that you can manipulate however you want! In my video, I just shrunk it down to 0 by 0, delayed and then brought it back to size using jQuery animate functions.
If you are viewing this blog on a supported browser, you should see yourself below. If you see nothing, it’s because you aren’t supported. I could wrap in a try catch but it’s late and I’m lazy.
In Wes’s video, he does some really cool stuff by adding effects to the stream. I would write a blog post on that, but you should come to FluentConf and check out Wes’s session instead.
A special thanks to Wes Bos for reviewing this post and pointing out that Opera does in fact have support for getUserMedia as well.
This past week I had the pleasure - and it was a pleasure - to visit the fine city of Sandusky, Ohio. Now up until this point, all I’ve known about Sandusky is this…

We were at the Kalahari Resort for CodeMash. This is a fabulous place by the way. Not only is it a fantastic indoor water park, but they have several restaurants, a wicked awesome candy shop and an arcade that will blow your mind. And your wallet.
CodeMash itself was epic. Unfortunately, being at an indoor water park does not mean you actually get to GO there. We spent almost all of our time at the conference, and since I was actually helping to proctor the event, I stayed pretty busy and didn’t get to attend many sessions.
I did make it to one session though that had a major impact on me.
Brandon Satrom did “CoffeeScript Is For Closers”. Brandon recorded a version prior to CodeMash and you can find the video here. I highly recommend watching it. The session is outstanding.
I had tried CoffeeScript in the past and found it frustrating. I found it frustrating for a couple of reasons.
1. How exactly do you use it with your project?
I get it. It’s a small language that compiles to JavaScript. It removes curly braces and semicolons. Great. Now how do I get it into Visual Studio or my Rails project? I had tried some third party plugins which I found disappointing because I couldn’t figure out how to use them.
2. My favorite patterns aren’t working anymore
I tend to develop using the same sort of JavaScript patterns over and over again. These patterns essentially stopped working with CoffeeScript because I couldn’t figure out how to structure them. No matter what I did, I couldn’t get CoffeeScript to write the JavaScript that I wanted. So I figured, why not just write the JavaScript myself?
If you have this problem, watch Brandon’s video as he will show you what to do. That’s not the point of this post.
What I learned about CoffeeScript is that it enforces some JavaScript best practices on you. If you aren’t prepared for this, it can be just a tad bit confusing. When I got home, I gave CoffeeScript another try and here is what I learned about how to recreate my favorite pattern in JavaScript, which is the Revealing Module.
Revealing Module
This is my absolute favorite way to structure my applications. The idea here is that you declare a variable which you set to a function. That function returns a variable which has methods. Each of these methods is public. Any functions not returned on that variable are private.
Let’s take a look at a sample revealing module.
JavaScript
This simple module is a logger. When it is intialized, I pass in a jQuery object representing the DOM element on the page where I want content to be logged. The init() and log() functions are public. The write() function which actually does the work, is not.
Additionally, I pass in the jQuery library to the main function and set that to $. It’s a good idea to not just assume that $ is always jQuery. But it should be.
CoffeeScript
My first run at this with CoffeeScript was a disaster. This is what I did…(CoffeeScript is on the left and JavaScript is on the right)
There is so much wrong with this, I just don’t know where to start.
Let’s start with the fact that when you run this, pub is undefined. What? I thought in CoffeeScript you just started rocking with variables without having to declare anything.
Yes, but in this case that you are referencing a variable on a variable that does not exist, you need to first define the variable. Ok, I can do that…
Now pub is defined, but if you look at the JavaScript that’s getting generated, the last thing returned is the Write function. That’s the ONLY thing I don’t want returned. You can see how this gets frustrating.
To fix this you can just return pub - or if you want, just type the word pub. CoffeeScript returns the last thing by default. Fine, pub.
Now the right thing is being returned out of the function. But here comes the “Best Pratices”.
Normally, we would reference this logger variable as logger.init() and then logger.write(). After we have loaded the JavaScript file, it should be available. But it’s not. Why not?
Notice that CoffeeScript is enclosing this whole variable logger in an anonymous function. It then executes call(this). What this basically does is protect the global namespace, and make sure that this = this. It can be tricky to keep up with exactly what this is equal to in JavaScript because it may be changing with the current scope. CoffeeScript is ensuring that this is in fact the global this when the function executes.
This is where I learned an important lesson. CoffeeScript protects the global namespace at all costs. It’s basically saying “You’re mom doesn’t live here. Don’t leave your crap lying around”. In “JavaScript, The Good Parts”, Crockford recommends prefixing variables that are going to go onto the global namespace with something like MYAPP. I don’t like that, but the point is that you aren’t just shoving things that could overwrite each other onto the global scope. CoffeeScript is protecting the global namespace by wrapping my variable declaration in a closure. As soon as the function is exited, it’s no longer available.
Now that we have talked about why you shouldn’t put things in the global namespace, let me show you how to put something in the global namespace. 
Let’s take a page right out of Jeremey Ashkenas own playbook. He wrote CoffeeScript btw.
Having a look at Underscore.coffee, you can see that the first thing he does is assign root to this. Then, he assigns his underscore variable to the root. This makes the _, and all of it’s functions available off the global namespace.

Passing in jQuery becomes different as well. Since the whole thing is wrapped in an anonymous function, we don’t need to pass in jQuery like we would with JavaScript. Instead, we can use the CoffeeScript do, which will create a closure around the logger function, allowing us to pass in jQuery there.
Here is what the revealing module looks like all finished.
Now that I know what CoffeeScript is going to do, I’m much more inclined to use it. I’m actually looking forward to using it because it makes code much easier to read. Go look at underscore.coffee and see how easy it is to follow. It’s brilliant how this works really. Not only does it compile down to JavaScript, but it teaches you quite a bit about JavaScript in the process.
A special thanks to Dan Mohl who gave me input on this article and contributed to some of the content, including cleaning up the final example.
EDIT
This is what I love about blogging. Steve Howell provided us with a super sexy and more terse example in this gist from his comment below. Thanks Steve!
I did a quick 15 minute presentation on JsFiddle Tips And Tricks and I was surprised at how many people had not even heard of JsFiddle. I think 3 or 4 hands went up in a room of nearly 100.
Of course, you do have to account for the 75% of people who just don’t answer questions in a group setting. That’s cool. I’m that guy sometimes. Especially if I haven’t been paying attention to what you are saying.
So assuming 25% of you haven’t heard of JsFiddle, that’s unacceptable.

JsFiddle is a browser based application created by Piotr Zalewa for creating snippets of HTML/CSS and JavaScript that you can version and share with others. It’s good for so many things and I use it pretty much every day. I have a fluid application setup just for JsFiddle. I also made an icon for it. Which I copied from Google. Ok, so I didn’t “make” it - I resized it. Which coincidentally is about the extent of my design skills. Just right-click that nifty JsFiddle PNG to the left there and save it. You will get the full PNG with transparency.
With JsFiddle, you have no need to create scratch or throwaway projects just to build a POC or prototype some idea. The syntax highlighting and auto-indentation support is really impressive for a web based application. In fact, the text editing capabilities are what really set it apart. It’s got a lot of obvious features, but some of the nicer ones aren’t as obvious.
StackOverflow is such a great way to get answers and help others out. It’s really redefined how we get solutions to our problems with some parameters around the validity of an answer. One thing that will really scare people away from trying to answer your questions, is you post something with 250 lines of code. It’s just too much for the eyes. However, you can create a simple fiddle in JsFiddle and it’s much easier for people to not only debug your code, but also give you an answer by forking your code and then providing the link to the fix.
I hope that StackOverflow will consider direct JsFiddle integration. It’s a subject that’s already been broached on meta.stackoverflow.com
Once you create an account and login to JsFiddle, you can create templates by adding in resources under the “Manage Resources” section - like external js/css libraries.

Drag the link to the fiddle to your toolbar in your respective browser and when you need to write a new fiddle with those same references, you just click the link, fork the fiddle and go. I created several templates a while back for some commonly used resources and UI libraries.

You can embed fiddles from the “share” menu on JsFiddle. You can then share them directly in your posts. I do that ALL the time both here and on kendoui.com/blogs. The embedding is pretty simple and clear.
Hit the “share” menu and then select embed and copy the code. Then just paste the code into your site or blog post. That’s pretty simple.

Then it will look something like this in your page.
Once you have it in the page, you can adjust the tabs that the user sees by adding certain variables after the “embedded/”. You can add “result”, “js”, “html and “css”. Each of these is delimited by a comma. For instance…
…/burkeholland/JwDZN/embedded/result,js
would show only the results and js tabs in that order.
Sometimes the clutter of the JsFiddle windows interferes with debugging because you have to take the whole UI in the browser tools. You can get rid of all that by appending /show on the end of your fiddle. This will show you just the result and make debugging and inspecting elements a whole lot simpler.
Piotr has pointed out in the comments below that the “show” is not a good idea as it’s vulnerable to cookie stealing. Instead, he recommends using the “draft” feature. The only drawback to this is that you have to be a registered user. This is something you should do anyway. Once you have done this, you can clear away the jsfiddle interface by running jsfiddle.net/draft which will show the last executed fiddle without the jsfiddle interface.
JsFiddle actually contains built-in functionality for mocking ajax requests. This is good because developing in JsFiddle means you probably can’t get at your data. Even if you could, it’s going to be cross domain. You can solve that by doing some ajax mocking. While JsFiddle does contain it’s on mocking tools, you have to post the data that you want back. A better option for me has turned out to be using MockJax from AppendTo in your fiddles for Ajax Mocking. Here is a sample fiddle where I am mocking some Ajax. Here is also a great article from AppendTo on how to use this library.
If you have a massive JavaScript library that you wrote and want to include, instead of pasting everything in the JavaScript pane, just create a public link in DropBox and reference the URL in the “Managed Resources” pane. You can use your DropBox as a CDN by sticking stuff in the public folder. I have a folder in mine called CDN where I stick all of the large libraries that I need to reference from JsFiddle. These would be libraries that aren’t already hosted by an official CDN.
Check out cdnjs for a complete list of hosted JS libraries. Chances are that if you need it, they have it.
JsFiddle is great, but does come with some frustration as it gets laggy during peak times because EVERYONE is using it. It’s that good. And it’s free. You will find times when it takes so long to render that you are better off just using a scrap application. I realize though that this is one person’s project and speed means more servers and more servers means more cash. I just appreciate it for what it is and I use it as much as I can when it’s not under heavy load.
JsFiddle is a fantastic tool for quick and rapid prototyping, sharing, and troubleshooting. I use it frequently and find myself only newing up projects on my local box when I’m actually working on a real project, not the random code question in an email.
All this talk of HTML5 and where to begin? It’s such a loosely defined and weird world we live in these days. Since we can’t wait until 2020 to get moving, where do you start? Is there anything out there that just bundles the “fundamentals” of HTML5 up for you in a nice complete package. Something like a template.
Or maybe….A BOILERPLATE!?!
Well yes in fact there is.
You have probably already heard about HTML5 Boilerplate. It’s got all the goodies you need to start your HTML5 development included in a “template” of sorts. The problem is, it’s not specifically targeted at Visual Studio users and thusly kind of a bear to implement. It comes with all sorts of Ant Build and other confusing things that just don’t make a whole lot of sense to ASP.NET developers.
When I was headed up to TechDays Vancouver, I wanted to do a session on using the boilerplate and I thought I would create a project template. But somebody beat me to it! Which is great because they probably did a better job that I would ever do. So let me present you with Mother Effin HTML Site created by Jacob Gable. I don’t know much about Jacob except that his handle on ASP.NET Is jacob4u2. I’m guessing he’s a U2 fan, so Jacob - this one’s for you.
This is a Visual Studio 2010 project template, so all of you 2008 / 2005 (God forbid 2003?) people are out of luck. Also, it’s MVC. Webforms is just as good for HTML5 as MVC, it just happens that this is an MVC project template.
My recommendation on this is for you to first watch Paul do his thing on Boilerplate for the San Francisco UG. He’s going to explain what pretty much everything in the index and CSS is for. It’s a really good lecture and explains a ton.
I am going to run down through this project structure and the _layouts (master page for you webforms people out there), but it’s really just a rehash of what Paul has already said in the video above. You didn’t watch it!?!?
So when loaded, the solution explorer will look like this…
Let’s step through this thing and explain what each of these folders are. Some need no explanation because you would expect you might see them (App_Data), and others are going to be completely foreign.
Alright – moving on.
Lets pop open the _layouts.cshtml folder under Views/Shared and have a look.
The first thing you will see is some conditional IE hacks.
This looks like a mess, but it’s pretty simple. All this is doing is applying a style of ie6, 7 or 8 to your html element. Oh – and it defaults it to no-js. What in the world.
The idea here is that you can default something to no-js and if js isn’t running in the browser, you can handle that appropriately through CSS. You can also handle if it’s IE 6, 7 or 8 in your CSS in the same way. For instance, you might do this…
.ie6 {
display: none;
}
I’m TOTALLY kidding.
Next you will see some meta tags…
Oh golly, meta tags. The first one is something that IE wants. It has something to do with cross site scripting in utf-7 and the validator will complain if you don’t have it in the first 54 bytes of the file. Listen to Paul explain it because he does a much better job than me. Just leave it alone and forget about it. IE needs it.
On a side note, I’ve always wondered if this is related to the issue Rob Connery was experiencing here.
The next one is pretty cool because it does 2 things. First it tells IE to use the 8 or 9 rendering engine if it is in fact IE 8 or 9. That’s to stop that whole compatibility mode nonsense that falls back to the IE 7 rendering engine and effectively breaks everything. By the way, compatibility mode is the default for apps in the intranet zone. This overrides that.
The second says “If you have Chrome Frame installed, use it”. That’s the chrome=1. It won’t prompt the user for an install, but does use the frame if it’s there. A nice to have.
Adding a description and author to your site is just good SEO.
The viewport business tells it to scale the app to the mobile device viewport. That’s all.
Alright, cross off the meta, and moving on.
Now this is some really cool stuff. This is SquishIt that we talked about earlier. It’s Justin Etheredge and it works great. Simple specify what CSS files you want to include here. As long as you have debug = true set in the web.config, you will get all the files separate. As soon as you set debug = false in the web.config, it’s going to combine and minify your CSS and give it a random name. I love SquishIt. Well done Justin. You will see SquishIt again down at the bottom.
Next is a Razor tag that includes custom head content on the fly if you have a partial or something else you want thrown in the header. This is MVC specific, not boilerplate.
This next section is pretty much explained by the comments:
These are two JavaScript libraries that we need ASAP, hence they are in the header. Modernizr is feature detection for your browser and when you run your application, your html tag will look something like this…
…and that frankly is pretty daunting the first time you see it. It’s just adding classes to your html showing you what features you support so you can respond appropriately in your CSS. Notice that no-js was replaced by js? We have to default to no-js because if JavaScript is turned off, Modernizr can’t run.
That screenshot is from Chrome. If you have IE 6, 7 or 8 it will look similar but with a “no-” in front of pretty much everything.
And now the body…
Nothing fancy here. Just a standard MVC layout with a logindisplay that you will probably delete straight away. The @RenderBody renders the views into the contents of the main div.
Notice the semantic HTML5 tags? Header? Footer? <Cartman>Sweeeeet</Cartman>
There is some super interesting stuff happening in these jQuery include tags. The first of which is a protocol relative URL. It’s basically saying that if the site is running on http, use that to fetch from the CDN. If it’s running on https, then use an https prefix.
The other thing here is that second script tag which basically does a test to see whether jQuery exists. It’s a fallback in case the CDN is down. CDN’s don’t go down I’m pretty sure. I personally don’t think this is necessary, but people much smarter than me do. If jQuery wasn’t loaded from the CDN, it writes a script include to a local copy. A neat idea, but I just don’t think it’s practical.
ANYWHO.
Some more SquishIt for your JavaScript and a render section in case you want to render in some scripts on the fly with a partial view.
And the grand finally – a Google Analytics script block for you to uncomment and stick your own UA ID in.
Whew – we made it through the master page! Only a few more things of note…
So that’s the HTML5 Boilerplate in Visual Studio. It’s a bit out of date and a bit ported. Well, a whole lot ported but still a great place to start your HTML5 development if you are using Visual Studio and MVC.
If you want to see the application we built at the session in Vancouver, you can see that here.
Wow! What an amazing trip I had this past week to Vancouver. I learned about Poutine, Japadogs and the shared disdain for Nickelback that we all have. I really enjoyed the beautiful city of Vancouver and all the really nice people that I met there.
I had the privalege - and it really was a “privilege” to attend the Make Web Not War event that Microsoft puts on. If you aren’t familiar with Web Not War, it’s a meetup that Microsoft puts together where all web technology is dicussed, regardless of what technology you are using. Everyone just gets together and talks about the cool stuff they are doing on the web. I love to see Microsoft supporting the web community at large. It was great to be a part of something where we were not .NET or PHP developers, but simply web developers. It honestly felt like we were one big team. A great sense of comradery. If you missed Web Not War, I highly recommend you make it your priority to attend the next event.
As promised, here is a revised list of HTML5 resources as well as the sample project we built in the second session and the deck from the first session.
Who has two thumbs and hooks up Canadians with sweet HTML5 resources? This guy!

Here we go….
The Deck From TechDays Is Here. The deck from the second session isn’t posted because, well, there really wasn’t one. It was all demo baby.
Dead simple and free Azure hosting for your .NET web applications from App Harbor. These guys put the “cious” in delicious. No more excuses. Write that killer app and deploy with no cost to you. That’s how it should be.
We built a pretty rockin demo application using Geolocation and some nifty CSS3 concepts. You can download that entire project here. Remember that it’s built on the MotherEffin HTML5 Site, so you may need to install the .vsix first.
What are you waiting for!?! Seriously, stop reading this and start building some HTML5 awesomeness. It’s super easy and getting easier. I enjoyed meeting all of you and look forward to hearing about what you are doing with HTML5.
Please feel free to follow me on Twitter, or email me directly.