Rey Bango

Web developer, honey badger

Interested in Ember.js? Check out my Tutorial Series.

ember-productivity-smWith the concept of web-based single-page apps really picking up steam, I started looking into frameworks that would make building them easier. Ember.js is one of these and I’ve really grown to like it. It does have a learning curve but it’s power and flexibility make it worthwhile. I’m also good friends with Yehuda Katz & Tom Dale who are the leads for Ember so I can ping them for feedback regularly.

As I’ve gone along learning Ember, I’ve created a series to help others based on my experiences. If you’re interested in Ember, checkout my tutorials below:

Getting into Ember.js – Part 1
Getting into Ember.js – Part 2
Getting into Ember.js – Part 3
Getting into Ember.js – Part 4

Ember Support

If you need help, be sure to join the Ember discussion forum. Lots of smart Ember developers there.

The Results of my Essential Tools, Libs and Frameworks for Front-End Development Survey

Two days ago, I put up a simple survey that asked what essential tools, libs and frameworks you were using for front-end development. I closed out the survey last night a little before 9pm EST and after getting 1000+ responses. I now want to share the results.

Why Am I Doing This?

As I’ve mentioned, this was an incredibly unscientific survey and not meant to determine which tool is best. Just which tools seem to be in heavy use.

I’m doing this to help web developers (myself included) stay on top of commonly used tools. Since change constantly but at least this gives a snapshot of what’s frequently used.

A couple of people buzzed me (some complaining and eluding bias), because I hadn’t listed “x” tool or lib in the survey. The survey wasn’t meant to be all-inclusive and if you look at the “Other” section below, you’ll see how adding everyone’s favorite tool would’ve been impossible. That’s what the “Other” option was for. Ultimately, instead of looking at what wasn’t there, you should read this for what was selected to determine if you need to get up-to-speed on specific tools.

The Process

After closing the survey, I removed all blank records and then went entry by entry to factor in the “Other” submissions and list out tools not originally added on the survey. I did my best to list every technology mentioned although it’s quite possible I may have missed something. If I did, it was purely accidental.

I ended up with 1031 total responses that I felt were good submissions. The results shown below for the main list was based off of what Google Docs provided. I didn’t do those calculations but I have to assume they’re correct.

Important to note is that the following options were added after 218 people had already replied so those values could’ve been much higher if added at the beginning. This is evident in Git & Coffeescript’s high numbers despite being added late.

  • LESS
  • Git
  • ExtJS
  • Ember.js
  • prefix-free
  • JSBin
  • JSFiddle
  • dabblet
  • Kendo UI
  • Wijmo
  • Coffeescript
  • YUI

Results from the Main List

Results from the “Other” Submissions

The ones listed below were submitted via the “Other” option and not on the main list.

A note about Enyo

EnyoJS is a framework released by HP which looks to have come out of the great work done by Palm. I haven’t used it and don’t have an opinion whether it’s actually awesome or not. I’ve held off on including it in these stats, though, because there was a high number of out-of-place submissions for it and they seemed clustered together around the same time. Additionally, MANY were single Enyo submissions with no other option chosen. Just seemed too odd to me but I’ll put out the data and if someone else wants to publish, go for it.

The Raw Data

Here’s the raw data from the survey. Please feel free to use it as you like and I hope it helps you out.

Raw Data from the Survey (.csv)

Essential Tools, Libs and Frameworks for Front-End Development. What are you Using?

UPDATE: The poll is now closed. You can see the results in this blog post.

I want to compile a list of the most common tools, frameworks & libs web developers are using today. Things seem to change daily with new, cool, and helpful projects announced all the time. It’d be great to nail some of these down as a reference.

Examples:

jQuery
Backbone
Underscore
Grunt
Mocha
RequireJS
HTML5 Boilerplate
Modernizr
SASS
Compass

Rebecca Murphey took a stab at this a couple of months ago.

So, what are you using that makes your front-end dev insanely easier?

iOS to IE10 Metro: Building Cross-Browser Plugin-Free Experiences

I’ve had the good fortune of working with my friend Jonathan Sampson recently on figuring out how to help developers build plugin-free experiences. With IE10 Metro going plugin-free, it’s incredibly important to document steps to help developers provide their users with great experiences without the need for proprietary 3rd party add-ons.

If you’ve built a plug-in-free browsing experience for the iPad, a few changes will make it ready for the new IE10 plug-in-free experience on Windows 8. As more browsers adopt the plug-in-free approach, now is a good time to start thinking about it. I’ll show you how to do this in a few steps below by writing code that works well in all modern browsers.

Today we’re going to work with a MSNBC plug-in-free experience for rich media. It breaks down to two things: styles and scripts.

To modify the files of MSNBC, I will be using a proxy application known as Fiddler. You can download this tool from http://fiddler2.com. This tool allows me to modify remote files as though they were on my local machine. If you have direct access to your own site, you can ignore Fiddler, and work directly with your files. Fiddler provides a great way for testing changes without the risk of breaking your live site.

Step 1: Declare Standards mode and valid markup for modern browsers

In order to use the HTML5 elements we’ll be utilizing below, you’ll first need to ensure that you are operating in standards mode. One way to ensure this is to include the HTML5 doctype at the top of your document:

<!DOCTYPE html>

Step 2: Update your CSS vendor prefixes

The CSS language is constantly in a state of change as new features are suggested, updated, and standardized. In order to allow developers to learn how to use these new features, browser vendors typically offer experimental implementations via prefixed properties.

A key part of using vendor prefixes responsibly is to ensure that prefixes from each vendor are included in your site to allow for the broadest level of feature support. In many cases, especially when building an iPad-centric site, you may have focused solely on -webkit properties, omitting the prefixes which target other browsers such as -o, -ms, and -moz. The end result of this is that you greatly limit the target devices that can render your plugin-free site to as well as provide a degraded experience for users of other modern browsers, many of which could serve up equally engaging functionality.

For instance, we find the following on MSNBC:

background: -webkit-gradient(
  linear,
  left top,
  left bottom,
  color-stop(1, rgba(192,192,192,.6)),
  color-stop(0.5, rgba(0,0,0,.6))
);

With the growing trend towards an HTML5 plugin-free experience, it’s important to expand these rules to provide the vendor prefixes of other major browsers as well.

background: -webkit-linear-gradient( 
  top, rgba( 0, 0, 0, 0.0 ) 0%, rgba( 0, 0, 0, 0.6 ) 50% );
background: -moz-linear-gradient( 
  top, rgba( 0, 0, 0, 0.0 ) 0%, rgba( 0, 0, 0, 0.6 ) 50% );
background: -ms-linear-gradient( 
  top, rgba( 0, 0, 0, 0.0 ) 0%, rgba( 0, 0, 0, 0.6 ) 50% );
background: -o-linear-gradient( 
  top, rgba( 0, 0, 0, 0.0 ) 0%, rgba( 0, 0, 0, 0.6 ) 50% );
background: linear-gradient(
  top, rgba( 0, 0, 0, 0.0 ) 0%, rgba( 0, 0, 0, 0.6 ) 50% );

While more verbose but the benefits to broad browser feature support certainly outweigh the extra typing involved. In addition, there are a number of great tools that can break down this workload, such as SASS and Compass, -prefix-free, or even CSS Snippets in the upcoming Visual Studio 2011.

Also, if you’re working predominantly in JavaScript and would like to save time determining which features are supported by your client’s browser, review the instructions in A Best Practice for Programming with Vendor Prefixes on the IEBlog.

Step 3: Get rid of browser sniffing methods

There are two methods used to determine what the user’s browser and device are capable of. One method, which unfortunately is somewhat popular, is browser sniffing. This method consists of examining the navigator object for certain patterns or values.

if ( navigator.userAgent.indexOf("iPad") > -1 ) {
  // Load HTML5 Experience
} else {
  // Load Flash Experience
}

The above code looks at the user agent string for the value “iPad”, and if found delivers a plug-in-free HTML5 experience. Otherwise, it’s assumed you are on a device that has Flash installed. This will result in a broken experience for non-iPad users who are browsing with plug-ins disabled, even though their browser is capable of handling HTML5 features.

Here is an attempt to find the version of Internet Explorer.

if ( tests.IE ) {
  j = /msie.(\d\.\d+)/i;
  k = navigator.userAgent.match(j)[1];
}

The user agent string is tested for a pattern that attempts to target the version number. This pattern looks for a single digit, followed by a period, followed by any number of additional digits. While this test will find values like “MSIE 8.0” and “MSIE 9.0”, it will not identify the latest version of Internet Explorer, which identifies itself as “MSIE 10.0”, since only one digit is expected before the period.

These are just a couple examples of why browser sniffing is not a best practice. The user agent string is not immutable – it is a read-write value that is easily changed by plugins, or even the user. Most modern browsers include the ability to easily change this value from their development tools, which some users take advantage of to get around poorly-developed websites.

If we disable plugins, or visit MSNBC from a device/browser that doesn’t have Flash, we would expect it to attempt a plug-in-free experience. Unfortunately, this is not the case. Rather than seeing an HTML5 experience, we’re instead asked to download Flash. This is because the site puts the user in one of two categories: an iPad user, or a Flash-enabled user.

Feature Detection

Rather than trying to guess what a browser is capable of by sniffing its user agent string (which will fail you eventually), it is much wiser to actually test features directly in the browser. If you wanted to test the browser’s ability to deliver video and audio via HTML5, you could actually attempt to create these elements via JavaScript, and see if the browser understands them. This practice is called feature detection.

if ( !!document.createElement(“video”).canPlayType  ) {
  // Load HTML5 Video
} else {
  // Load Flash Video
}

In the above example, we start by testing whether the canPlayType method exists on our newly-created video tag. We’re using double-negation to cast the response to a boolean. If the browser understands what a video element is, the canPlayType method will be present. If the video element is unknown to the browser, the canPlayType method will not exist. If this test passes, we load our HTML5 video. If the test does not pass, we attempt to load Flash. Deeper feature detection could take place here, since Flash may not be on the machine, or may be disabled.

Feature detection is the preferred method of determining what a browser is capable of, since there is no guesswork involved. If the browser passes properly-constructed tests, it absolutely supports the features you would like to use.

Many great tools exist to provide feature tests for you. Once such tool, which provides over 40 tests, is Modernizr. This tool creates a global object called “Modernizr” which contains the results of your tests. With Modernizr, testing for HTML5 video support is extremely easy:

if ( Modernizr.video ) {
  // Load HTML5 Video
}

MSNBC engages in browser sniffing to see if the device accessing the page is an iPad or not. Our first step is to remove the browser sniffing code, and replace it with feature detection code.

Before we can modify browser sniffing code, we first need to locate it. While in Internet Explorer, pressing F12 will pull up our Developer Tools. Within the tools, open the Script tab and do a search for “userAgent”. This search will seek out any instance of this property name in all of the site’s script files. We’re interested in the result from line 41 of http://www.msnbc.msn.com/id/37156949/.

Now that we know what we want to edit, we can open up Fiddler and load up our traffic. Once Fiddler is opened, perform a hard-refresh (Ctrl+F5 in IE) on the MSNBC page. This results in all of the page sessions being listed in Fiddler.

Looking carefully, you’ll notice our resource is the third from the top. Next I will setup an AutoResponder for this session file so that anytime it is requested, my own custom file is substituted in the place of the server response:

  1. Right-click this session and select “Decode Selected Sessions” from the context menu.
  2. Select the AutoResponder tab on the right.
  3. Click the “Enable automatic responses” checkbox in the AutoResponder tab.
  4. Drag the selected session from the left panel into the AutoResponder tab.

At this point, you should have an entry within your AutoResponder tab with the following rules:

  • If URI matches: EXACT:http://www.msnbc.msn.com/id/37156949/
  • Then respond with: *200-SESSION_3

Right-click the entry in the AutoResponder and select Edit Response. In the popup that follows, switch to the SyntaxView tab where we will find the source for this file. As expected, line 41 contains our browser sniffing code:

if(!(navigator.userAgent.toLowerCase().indexOf("ipad")>-1)){
  // Flash Experience
}

Rather than test the contents of the userAgent, we’re going to instead look for support for the HTML5 video tag. Switch the above condition to the following:

if ( !document.createElement("video").canPlayType ) {
  // Flash Experience
}

This test checks to see if we cannot use the video element. If canPlayType comes back as undefined, it will be cast to true and the first code block will be entered, setting up the Flash experience.

Step 4: Update touch and pointer events

Safari supports both a touch event model and a mouse event model. Internet Explorer 10 groups touch, mouse, and stylus events into a single abstract item known as a pointer. In fact, Internet Explorer 10 is the first browser to work for all input types, across all devices. This abstraction cuts down drastically on the amount of effort involved to determine which event model you ought to bind to and how to detect user-interaction. This pointer is then handled through MSPointer events. If necessary, you can determine the type of pointer by accessing the pointerType property.

Due to the fact Internet Explorer doesn’t support Apple’s proprietary event model, which includes touch events like touchstart, touchmove, and touchend, MSNBC’s event listeners will need to be amended to listen for MSPointer events like MSPointerDown, MSPointerUP, and MSPointerMove.

Due to the difference in event model implementations, use a feature detection tool like Modernizr or code like this to target all major event models:

if (window.navigator.msPointerEnabled) {
  myCanvas.addEventListener("MSPointerMove", paint, false);
} else {
  myCanvas.addEventListener("mousemove", paint, false);
  myCanvas.addEventListener(“touchmove”, paint, false);
}

MSNBC only supports touch events, which we will need to change so that visitors who happen to be using a mouse can still interact with the page:

Our events are tied up in http://www.msnbc.msn.com/id/43662671/15:

document.addEventListener("touchstart", touchHandler, false);
document.addEventListener("touchmove", touchHandler, false);
document.addEventListener("touchend", touchHandler, false);

We’re going to update this to include the MSPointer events as well:

if (window.navigator.msPointerEnabled) {
  document.addEventListener("MSPointerDown", touchHandler, false);
  document.addEventListener("MSPointerMove", touchHandler, false);
  document.addEventListener("MSPointerUp", touchHandler, false);
} else {
  document.addEventListener("touchstart", touchHandler, false);
  document.addEventListener("touchmove", touchHandler, false);
  document.addEventListener("touchend", touchHandler, false);
  document.addEventListener("mousedown", touchHandler, false);
  document.addEventListener("mousemove", touchHandler, false);
  document.addEventListener("mouseup", touchHandler, false);
}

First we’re checking for the presence of pointers. Since the MSPointer covers the mouse, fingers, and pens, we don’t need anything else besides them. We fall back, if necessary, to provide both touch and mouse events.

Next we need to create cases for these event types in http://www.msnbc.com/id/44937131/. Currently, MSNBC starts with the following:

if ( event.type == "touchstart" ) {
  /* Start drag logic */
} else 
if ( event.type == "touchmove" ) {
  /* Drag logic */
} else 
if ( event.type == "touchend" ) {
  /* Complete drag logic */
}

We’ll modify this to listen for all of the registered event types:

if ( event.type.match( /(down|start)$/i ) ) {
  /* Start drag logic */
} else 
if ( event.type.match( /move$/i ) ) {
  /* Drag logic */
} else 
if ( event.type.match( /(up|end)$/i ) ) {
  /* Complete drag logic */
}

The above uses the match method and a series of regular expressions to determine which event was raised. If the event raised ends with a case-insensitive “down” or “start”, we begin our drag code. If the event ends with a case-insensitive “move”, we perform the actual drag logic itself. And lastly, if the event ends with a case-insensitive “up” or “end”, we end our dragging event. Note: other events may be caught here as well, like onresizeend and keyup. Be sure to consider this in your project.

The above is an implementation of Ted Johnson’s solution in Handling Multi-touch and Mouse Input in All Browsers.

The drag logic itself initially relies upon the event.targetTouches TouchList. This member does not exist in Internet Explorer. The drag logic attempts to gather the pageX and pageY properties from the first item in the TouchList, however in Internet Explorer these values are found directly on the event object.

var curX = event.targetTouches[0].pageX;

Using the logical OR operator, I instruct curX to hold the value of event.pageX as long as event.pageX is present on the event object. If this property is not found, look within the targetTouches list:

var curX = event.pageX || event.targetTouches[0].pageX;

If event.pageX is not found, we fall back to assigning the value of targetTouches[0].pageX to our variable.

Another important item to keep in mind is that this site initially responds to touchmove. When this event is raised while touching the playlist, the code attempts to reposition the playlist based upon your touch movement. There is no hovering when it comes to touch – you’re either touching, or you’re not.

Now that we have mouse events tied into this logic, we have introduced the possibility for hovering. So while touchmove is free to reposition our playlist when it is over the playlist, we don’t want to do the same for mousemove. In fact, we only want the mousemove event to reposition the playlist when the mouse button is pressed.

For further reading, and examples on how to target all browsers, see Handling Multi-touch and Mouse Input in All Browsers.

Testing both experiences

Recall our feature detection from earlier, how we first check to see if HTML5 video support is in the user’s browser. If it is, we give them HTML5. If it is not, we give them Flash. One easy way to test our work is to use a browser, or document mode, that doesn’t support HTML5 features. This is very easy to test with Internet Explorer:

  1. Press F12 to reveal the Developer Tools
  2. Change your Document Mode to Internet Explorer 7 Standards
  3. Refresh the page

If our feature detection condition was written properly, you should now be watching a Flash-based presentation. Switching your Document Mode back into Internet Explorer 9 Standards (or “Standards” if you’re using IE10), will return you to the HTML5 experience.

Get it Done!

Hopefully this post helps to define the types of changes that will allow your iOS site to work properly in IE10 Metro and other plugin-free environments. By including best practices such as feature detection and responsibly using vendor prefixes for great new features, you should be able to provide your users a great experience, regardless of which browser or device they’re using. To assist with testing in other plug-in-free environments, download Internet Explorer 10 (currently available only in the Windows 8 CP) and begin testing today!

Update: In the rush to get this post up, I realized that I forgot to thank and give credit to Jonathan Sampson for helping investigate and write about the great techniques mentioned above. He was a huge help in generating many of these great techniques. Thanks JS!

Site Pinning: Rotating Overlay Icons for Multiple Service Notifications

In my last post, I went over how to use IE9′s Site Pinning API to implement overlay icons to enhance user notifications. The demo focused on how to display a numeric icon to indicate when a specific event (e.g.: messages in an inbox) had occurred.


Pinned site with overlay icon

It’s a really great way of letting your users know that there’s pending information for them to check into. But what happens if your site offers multiple types of notifications? With websites offering so much functionality nowadays, it’s pretty common for them to also serve up multiple types of notifications, from friend requests and event reminders to new messages and game invites.

Rotating Multiple Overlays Icons

The great thing about the Site Pinning API is that it’s very flexible and through some JavaScript magic, you can easily display multiple overlay icons for the various services you have. In this demo, I want to rotate through 3 different overlay icons that alert the user to pending messages, requests and actions.

As before, I had to flex some of my artistic talent by creating the overlay icons using the x-icon editor. I created 5 of each and here’s how the first three look:

The code changed slightly from the last demo in order to accommodate multiple bits of data per fetch. While previously, I was only fetching one piece of data, in this demo, I’m returning 3, one for each notification type:

 myPin.init([{ "data" : [{ "label" : "Messages", "ntype" : "M", "num": 2 }, { "label" : "Requests", "ntype" : "R", "num": 1 }, { "label" : "Actions", "ntype" : "A", "num": 3 }] },
		        { "data" : [{ "label" : "Messages", "ntype" : "M", "num": 1 }, { "label" : "Requests", "ntype" : "R", "num": 5 }, { "label" : "Actions", "ntype" : "A", "num": 2 }] },
		        { "data" : [{ "label" : "Messages", "ntype" : "M", "num": 5 }, { "label" : "Requests", "ntype" : "R", "num": 1 }, { "label" : "Actions", "ntype" : "A", "num": 4 }] }
			   ]);

As a reminder, the method getData() simulates grabbing remote data. So if we look at the data above, we can simulate pulling back three distinct bits of data. This is why we call the method every 10 seconds using setInterval. This allows us to see how notifications might look over a period of time.

setInterval(function () { myPin.getData() }, 10000);

The next thing that changed is the use of a timer to allow a slight delay while rendering the overlay icons. Using setTimeout() provides enough of delay so that an individual overlay icon is visible to the user before rotating on to the next icon. If we didn’t have this delay, the rotation would be way too fast to provide any useful notification. If we look at the following image, we can see what the notification will look like:


Overlay icon showing numeric notification

This is accomplished via the following code:

// Grab the current set of data...
currData = this.dataBin[this.currIndex++].data;		
		
/* We're going to display a new overlay every x number of seconds to display a new overlay icon so
   let's loop through the data elements for the current set of data... */
for (var i=0; i < currData.length; i++ ){
					
	(function(idx) { setTimeout( function(){ myPin.dispOverlay( currData[idx] ); }, 1000 * idx); }( i ));					
					
}

Here’s what’s happening. In the first line, I grab the current set of data that holds all of the notification information (messages, requests & actions). That data looks like this:

[{ "label" : "Messages", "ntype" : "M", "num": 2 }, 
{ "label" : "Requests", "ntype" : "R", "num": 1 }, 
{ "label" : "Actions", "ntype" : "A", "num": 3 }]

I loop through each group of data and assign a timer using setTimeout() that will call dispOverlay() at ~1 second intervals. That’s the magic code that allows for the gradual icon rendering delay I mentioned before. The expected functionality is that the “messages” icon will render followed by the “requests” icon 1 second later, and then finally the “actions” icon.

Now, you might be wondering why I have an anonymous function wrapping the setTimeout(). It’s because I have a closure within setTimeout which can cause a common scoping issue in which the variable ‘i’, which I use to grab the current index of data, will only be updated to the last index value. James Padolsey has a great explanation on it and thanks to John David Dalton for helping me troubleshoot this.

The final change is in dispOverlay() in which I need to determine which overlay icon needs to display. Since I now have three different types of notifications, I need a conditional statement to determine the type and build the correct icon name:

if (theData.ntype == "M") {
	oImg = "images/messages-" + theData.num + ".ico";
} else if (theData.ntype == "R") {
	oImg = "images/requests-" + theData.num + ".ico";
} else if (theData.ntype == "A") {
	oImg = "images/actions-" + theData.num + ".ico";
}

This checks the type and serves up the right icon based on the type and the number of notifications pending for that type.

The Demo and Final Code

You can check out the demo by going here in IE9:

http://reybango.com/demos/sprotate/index.html

When the page renders, drag the tab down to your taskbar and pin it. You should see a new window appear with your newly pinned site. Next, you’ll see the overlay icons appear in the taskbar and they should begin to cycle every 10 seconds.

Here’s the full source code. You can also download everything here.

<!DOCTYPE html>
<html>
<head>
<title>Pinned Site - Rotating Overlay Icons</title>
<link rel="shortcut icon" type="image/ico" href="favicon.ico" />
<meta name="application-name" content="Pinned Site Test" />
<meta name="msapplication-starturl" content="http://reybango.com/demos/sprotate/index.html" />
<meta name="msapplication-navbutton-color" content="#3480C0" />
<meta name="msapplication-window" content="width=1024;height=768" />
<meta name="msapplication-tooltip" content="Testing the Pinned Site API" />
<style>
body {
    background: none repeat scroll 0 0 #4492CE;
    font: 440%/1.4em 'Segoe Light',Segoe,'Segoe UI','Meiryo Regular','Meiryo',sans-serif;	
    color: #EDEFF4;
}

</style>

</head>

<body>

<div>
<h1>Pinned Sites</h1>
<p>Rotating Overlay Icons</p>
</div>

<script>

	var myData = [];

    var myPin = {

        currIndex: 0,
        dataBin: [],
		
        getData: function () {

			var idx = 0, currData = [], cntr = 0, theData;
		
            // Determines whether the current page was launched as a pinned site...
            if (window.external.msIsSiteMode()) {

				// Grab the current set of data...
				currData = this.dataBin[this.currIndex++].data;		
		
				/* We're going to display a new overlay every x number of seconds to display a new overlay icon so
				   let's loop through the data elements for the current set of data... */
				for (var i=0; i < currData.length; i++ ){
					
					(function(idx) { setTimeout( function(){ myPin.dispOverlay( currData[idx] ); }, 1e3 * idx); }( i ));					
					
				}
				
				if (this.currIndex > 2) { this.currIndex = 0 }
				
            }

        },

        dispOverlay: function (theData) {

            var oImg = "";

            // Is there any data?
            if (theData) {

                // Clear any preexisting overlay icon
                window.external.msSiteModeClearIconOverlay();

				// Render the overlay icon based on the data returned...
				if (theData.ntype == "M") {
					oImg = "images/messages-" + theData.num + ".ico";
				} else if (theData.ntype == "R") {
					oImg = "images/requests-" + theData.num + ".ico";
				} else if (theData.ntype == "A") {
					oImg = "images/actions-" + theData.num + ".ico";
				}				

                // Go ahead and create the overlay image and it's label...
                this.setOverlay(oImg, theData.label);

            }

        },

        setOverlay: function (icon, desc) {

            // Sets the overlay icons...
            window.external.msSiteModeSetIconOverlay(icon, desc);
            window.external.msSiteModeActivate();

        },

        init: function (myData) {

            this.dataBin = myData;
			this.getData();
			
        }

    };

    // This clears out any previously set overlay icons...
    window.external.msSiteModeClearIconOverlay();
	
    // Run it once to kick everything off...
    myPin.init([{ "data" : [{ "label" : "Messages", "ntype" : "M", "num": 2 }, { "label" : "Requests", "ntype" : "R", "num": 1 }, { "label" : "Actions", "ntype" : "A", "num": 3 }] },
		        { "data" : [{ "label" : "Messages", "ntype" : "M", "num": 1 }, { "label" : "Requests", "ntype" : "R", "num": 5 }, { "label" : "Actions", "ntype" : "A", "num": 2 }] },
		        { "data" : [{ "label" : "Messages", "ntype" : "M", "num": 5 }, { "label" : "Requests", "ntype" : "R", "num": 1 }, { "label" : "Actions", "ntype" : "A", "num": 4 }] }
			   ]);

    // This is only here because I want to simulate pulling data on a regular interval...
    setInterval(function () { myPin.getData() }, 10000);

</script>
</body>
</html>

Using Site Pinning and Overlay Icons for Enhanced User Notifications and Engagement

I was recently doing some testing of IE9′s Site Pinning API and found out about a cool bit of functionality that can enhance user notifications. If you’re not familiar with site pinning, it’s a great way to allow users to have easy and quick access to their favorite sites via the Windows taskbar. There’s a really nice overview on Beauty of the Web that explains how it works.

Keeping Users Up-to-Date

One of the features the API provides is the notion of notifications that can allow developers to provide alerts to end users. The functionality allows you to dynamically insert custom overlay icons that can alert users when an important bit of information is available. These overlay icons are rendered over the favicon that is pinned to the taskbar. If you look at the image below, you can see it in action:


Pinned site with no overlay icon


Pinned site with overlay icon

So if you think about the possibilities, any site that offers users an inbox, special deals or sends out time-sensitive alerts could use this notification capability to keep their users up-to-date and more engaged on the site. Sites like the Huffington Post have already discovered that users that pinned HuffPost spent 49% more time on the site.

The best part is that adding this capability is insanely easy.

Setting it Up

For this post, we’re not going to go into the basics of how to pin a site. If you want to learn more, here’s a GREAT resource for getting you up to speed quickly: BuildMyPinnedSite.com. In fact, I used that site to help get me up-to-speed on the basics and it’s well-worth visiting.

To add notifications, you’ll need a couple of things:

  • A cool favicon for your site. If you don’t have one, you can use the handy web-based X-Icon Editor to create one.
  • A set of overlay icons to use. The recommended size is 16×16.

The API is JavaScript-based and we’ll use the following methods:

window.external.msSiteModeClearIconOverlay()
window.external.msSiteModeSetIconOverlay()
window.external.msSiteModeActivate()
window.external.msIsSiteMode()

The window.external.msSiteModeClearIconOverlay method is used to clear out any previously set overlay icons. window.external.msSiteModeSetIconOverlay allows you to specify the name of the notification icon as well as a accessible description. Lastly, we’ll use window.external.msSiteModeActivate to flash the pinned icon to notify the user of the update. Lastly, window.external.msIsSiteMode will let us know if the page was launched as a pinned site, thus allowing us to better determine when to run the code.

For the overlay icons, I’m using five images that display numbers 1 through 5 respectively to designate the number of messages are in a user’s inbox.

The Code

The first thing I need to add is the reference to my favicon. Note that if you don’t add one, then the Internet Explorer’s icon will be used by default.

<link rel="shortcut icon" type="image/ico" href="favicon.ico" />

Next, I want to create some sample data to work with. What I want to do for my demo is to have the overlay icon dynamically change every 5 seconds to simulate a more real-world scenario. The data is a simple array containing JSON data in each element.

myPin.init([{ "num": 1, "label": "Label 1" },
                { "num": 2, "label": "Label 2" },
                { "num": 3, "label": "Label 3" },
                { "num": 4, "label": "Label 4" },
                { "num": 5, "label": "Label 5" }
                ]);

By setting a timer, I’ll be able to pull a new set of data every 5 seconds.

setInterval(function () { myPin.getData(); }, 5000);

The main thing to keep in mind is that I’m “simulating” getting data from some remote host. In reality, all that the myPin.getData() method does is use a running counter to grab a new set of data and render a new overlay icon:

getData: function () {
            // A function that just simulates returning a result set...
            var idx = 0;

            // Determines whether the current page was launched as a pinned site.
            if (window.external.msIsSiteMode()) {

                idx = this.currIndex++;
                this.currIndex = (this.currIndex < 5) ? this.currIndex : 0;

                this.dispOverlay(this.dataBin[idx]);

            }

}

As you can see, it uses the running counter var currIndex to determine which array element to grab and then passes the data to dispOverlay(). This is where we use window.external.msSiteModeClearIconOverlay() to clear out any previously displayed overlay icons and also generate a string for the actual icon name. You can see that the oImg var is created on the fly based on the data we’re using.

dispOverlay: function (theData) {

            var oImg = "";

            // Is there any data?
            if (theData) {

                // Clear any preexisting overlay icon
                window.external.msSiteModeClearIconOverlay();

                // Create the image string...
                oImg = "images/num_" + theData.num + ".ico";

                // Go ahead and create the overlay image and it's label...
                this.setOverlay(oImg, theData.label);

            }

}

That icon name, along with the accessible label text for the icon, is passed to setOverlay() which sets the overlay icon via window.external.msSiteModeSetIconOverlay and flashes the taskbar icon using window.external.msSiteModeActivate.

setOverlay: function (icon, desc) {

            // Sets the overlay icons...
            window.external.msSiteModeSetIconOverlay(icon, desc);
            window.external.msSiteModeActivate();

}

Test it Out

To test this out, it’s a simple matter of running your newly pinned page in Internet Explorer 9, grabbing the tab and dragging it down to your taskbar:


Tab being dragged to the taskbar


Pinned site with no overlay icon

Five seconds after the page has been pinned, the code will fire off the first notification and continue to cycle through the other icons every subsequent five seconds.


Pinned site with overlay icon

An important thing to remember is that the IE F12 Developer tools are available to you to use in debugging your pinned site. So if you run into quirks, simply press the F12 key and the tools will appear.

The Demo and Final Code

You can check out the demo I whipped up by going here in IE9:

http://reybango.com/demos/sitepinning/index.html

When the page renders, drag the tab down to your taskbar and pin it. You should see a new windows appear with your newly pinned site. Five seconds later, you’ll see the first overlay icon appear in the taskbar.

Here’s the full source code. You can also download everything here. The really great part is that it isn’t a lot of code to implement this. In fact, to use the API only required 4 method calls. The bulk of the code was to simulate pulling in data. And the “>impact on user engagement is certainly worth adding in the capability.

<!DOCTYPE html>
<html>
<head>
<title>Pinned Site Test</title>
<link rel="shortcut icon" type="image/ico" href="favicon.ico" />
<meta name="application-name" content="Pinned Site Test" />
<meta name="msapplication-starturl" content="http://reybango.com/demos/sitepinning/index.html" />
<meta name="msapplication-navbutton-color" content="#3480C0" />
<meta name="msapplication-window" content="width=1024;height=768" />
<meta name="msapplication-tooltip" content="Testing the Pinned Site API" />
<style>
body {
    background: none repeat scroll 0 0 #4492CE;
    color: #EDEFF4;
}
 
h1 {
    float: left;
    font: 440%/1.4em 'Segoe Light',Segoe,'Segoe UI','Meiryo Regular','Meiryo',sans-serif;
    margin-left: 10px;
    position: relative;
}
</style>

</head>

<body>

<h1>Pinned Site Test</h1>

<div></div>

<script>

    var myPin = {

        currIndex: 0,
        dataBin: [],

        getData: function () {
            // A function that just simulates returning a result set...
            var idx = 0;

            // Determines whether the current page was launched as a pinned site.
            if (window.external.msIsSiteMode()) {

                idx = this.currIndex++;
                this.currIndex = (this.currIndex < 5) ? this.currIndex : 0;

                this.dispOverlay(this.dataBin[idx]);

            }

        },

        setOverlay: function (icon, desc) {

            // Sets the overlay icons...
            window.external.msSiteModeSetIconOverlay(icon, desc);
            window.external.msSiteModeActivate();

        },


        dispOverlay: function (theData) {

            var oImg = "";

            // Is there any data?
            if (theData) {

                // Clear any preexisting overlay icon
                window.external.msSiteModeClearIconOverlay();

                // Create the image string...
                oImg = "images/num_" + theData.num + ".ico";

                // Go ahead and create the overlay image and it's label...
                this.setOverlay(oImg, theData.label);

            }

        },

        init: function (myData) {

            this.dataBin = myData;

        }

    };

    // This clears out any previously set overlay icons...
    window.external.msSiteModeClearIconOverlay();

    // Run it once to kick everything off...
    myPin.init([{ "num": 1, "label": "Label 1" },
                { "num": 2, "label": "Label 2" },
                { "num": 3, "label": "Label 3" },
                { "num": 4, "label": "Label 4" },
                { "num": 5, "label": "Label 5" }
                ]);

    // This is only here because I want to simulate pulling data on a regular interval...
    setInterval(function () { myPin.getData(); }, 5000);

</script>
</body>
</html>

Eloquent JavaScript is one of the Best JavaScript Books I’ve Read

The kind folks at No Starch sent me over a copy of the newly released book, Eloquent JavaScript by Marjin Haverbeke. I had already been recommending the namesake site as a must-read resource on my list of What to Read to Get Up to Speed in JavaScript so actually having the book was a welcome change. I know some people love to read stuff on the web but call me old fashioned in that I really like the feel of a book in my hands.

What I loved about this book is that it’s not your typical reference tomb. The basic premise is that it’s going to teach you proper constructs for writing solid JavaScript code as opposed to listing every method, attribute, data type or property ever included in the JavaScript language. It gets straight to the meat of JavaScript development, introducing you to the basic constructs of the language and then quickly diving into more complex topics such as partials and currying. This is all done in a step-by-step approach to give the reader an opportunity to not only digest the material but also see actual results in real-time. Definitely a great approach.

Differences Between the Site and the Book

As I mentioned the book is based on the great work that Marjin did on the namesake site. I’ve seen the site and absolutely love it but to me, I feel the book is a MUCH more organized version of his thoughts. The content is broken down into logical sections with better headers which makes conceptualizing specific areas much easier.

And again, I truly am partial to reading books instead of websites so for me, having the book was a real blessing.

What about JavaScript Libraries?

This book is really focused on the JavaScript language itself and not libraries. If you’re interested in really becoming a better JavaScript developer so you can take full advantage of your favorite library, then this book is a great choice. It’s a complementary selection.

My Visual Studio 2010 HTML5 Templates are Updated for jQuery 1.5.1 and Modernizr 1.7

I wanted to do a refresh of the Visual Studio 2010 HTML5 Templates I created last September. With jQuery now at v1.5.1 and Modernizr at v1.7, it was time for an update.

If you’ve already downloaded my original templates, you can simply overwrite those with the following files. If you’re new to this, then download the files and drop them into the folders I mention immediately below each file:

HTML5 Page Template with jQuery 1.5.1 & Modernizr 1.7

Drop this into “Visual Studio 2010 > Templates > ItemTemplates” folder

HTML5 Web Site Template with jQuery 1.5.1 & Modernizr 1.7

Drop this into “Visual Studio 2010 > Templates > ProjectTemplates” folder

Using the Templates

Once in place, all you have to do is select “File=>New Web Site” to use the new template:

To create a new HTML5 web page template, you’d select “File=>New File” to choose the HTML5 Page Template

What to Read to Get Up to Speed in JavaScript

There’s a discussion going on on the JSMentors JavaScript mailing list about books to read to get you to the next level. There’s been a lot of great feedback and suggestions thrown out and I wanted to offer up what I felt were good books/resources to carry you through the learning process. While I list a number of books in the Big List page that I created, narrowing it down into specific levels makes a lot of sense.

Note that some resources will overlap between levels. That should be expected as some books cover a wide breadth of language features. Also, I am NOT covering blogs in this post, only books (print and online). If you think something’s missing, please add it to the comments below.

Also, I’m not saying that you need to read every book mentioned below. These are books that I’ve read over the years and found incredibly useful so I’m categorizing them to make it easier for you to get going. I’ve done the legwork so need for you to do the same. Choose the books that you feel suit you.

Introductory

These are books that will give you the fundamentals of the JavaScript language and get you started:

Intermediate

Once you’ve gotten an understanding of the basics, it’s time to get a resource that will take you deeper and in many cases be your reference for years to come. These books fit that description.

Advanced

You have a firm grasp of the JavaScript language and now you want to step up your game. These books will help you get the knowledge you need to organize your applications and build maintainable code.

God Mode Reading

As Peter van der Zee likes to call it “godmode; the actual specification”. Want some deep reading and know every nook and cranny of the language. Here ya go:

Blogs

What if *I* had to Choose Just 3 Books

If I had to choose just three books to have in my stash, I’d go with the following:

Some may disagree with me on this but I’ve personally found each one of these books incredibly valuable. Professional JavaScript for Web Developers is a complete reference and covers EVERYTHING. All developers need a book like this. The book on Object-Oriented JavaScript is great to give you an understanding of leveraging one of the best features in JavaScript. Once you get past the basics, you’re going to want to identify key coding practices that make your code better and more maintainable. JavaScript Patterns helps you do that.

What would you guys choose?

Why We Built the JSMentors.com JavaScript Mailing List

I posted earlier this week about the launch of the JSMentors.com mailing list. So far the response has been amazing. The list has grown from 344 on Nov 29 to 900+ today. Just phenomenal growth and a testament to the need of the list. But where did this idea come from?

comp.lang.javascript Was Not for Me

I’ve been involved in the JavaScript community for some time, especially with the jQuery JavaScript library project. I’ve been fortunate to make a lot of friends who have helped me overcome many of the pitfalls and hurdles normally associated with becoming a JavaScript developer. As I began feeling more confident, I did what I feel most people do when they want to advance their skills to the next level and ventured over to comp.lang.javascript (CLJ). CLJ has a long history due to its roots in the newsgroup mediums which predated forums as the main method of communicating about many topics. I had heard that the developers there were top notch and you could find great content. To me, this was the obvious place to go. So I went. And I regretted it.

Everything people said was true. There are many incredibly smart and savvy JavaScript developers there; I would say some of the best in the world. The problem I encountered was a consistent lack of manners, courtesy and respect that completely overshadowed any of the conversations that were going on. I’m not alone in this feeling. And this seemed to be happening due to a small but vocal minority that tended to hijack any thread and turn them into their own chest-thumping diatribe. I’ve dealt with tough crowds before but even I was shocked by what was happening here. Couple that with the insane amount of spam being posted there, I knew that *I* wouldn’t be successful in this environment (CLJ) in spite of some of the great information being posted. Notice how I highlighted “*I*”. That’s because CLJ may be perfectly suited for others. I know several developers who participate and find it useful. It just wasn’t for me.

A Community Resource

So I began chatting with Asen Bozhilov about this and explained how I would love to see a list where anyone who wanted to become a better JavaScript developer could go to and participate in a courteous, respectful and professional environment. It was also important to have as many of the non-confrontational experts on CLJ serve as mentors and share their knowledge with people who genuinely wanted to learn but didn’t want to be shot down or berated due to their skill level. So Asen & I set about creating JSMentors.com. Asen is one of this super experts and he has very close ties with many of the experts on CLJ. After chatting with them a bit, many found this to be a great idea, especially since it offered them:

  • A chance to teach best practices to an ever-growing community of developers
  • A medium to publish content that they felt was important
  • An opportunity for the JavaScript world to meet these top developers and begin learning from some of the best

The important part was that each of these mentors understood that this list was going to be very different and that our goal was to nurture a community. And we made the rules of the list perfectly clear to ensure no confusion:

  • No insulting other subscribers
  • No posting racism
  • No spam publications

This had to be different from CLJ to work. It had to focus not only on the language but also the community.

JSMentors.com is Born

The list was launched with little fanfare. We wanted it to grow organically to see how people would react and that was a great tact. Since launching, we’ve steadily grown the mailing list as well as the list of mentors. The great thing is that we’re getting top-level developers involved who would never had considered participating in CLJ due to the tough nature of communication there. This was exactly what we wanted. A place where developers of ALL skill levels can go and exchange ideas in a professional setting. It’s not to say that occasionally there won’t be disagreements. That’s normal. But Asen & I actively monitor the list and we’re adamant about the rules we’ve set and maintaining a good list. Ultimately, we want everyone to become better developers and yes, I have a little selfish motivation myself as the opportunity to learn from so many top developers is one my drivers for this list. And I think that’s a good thing. :)

Learn JavaScript!

What to Read to Get Up to Speed in JavaScript.

The best books & blogs for learning JavaScript development. Broken down by experience levels!


My BIG LIST of JavaScript, CSS & HTML Development Tools, Libraries, Projects, and Books.

Constantly updated with the latest and greatest tools. Check it out!

Categories

Rey Bango is Stephen Fry proof thanks to caching by WP Super Cache