Rey Bango

Web developer, honey badger

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

Presenting at the jQuery Summit Online Conference on November 17th

Next week, Environments for Humans will be hosting their 2nd jQuery Summit Online Conference and what a great event it will be. The speakers (myself included) are just an who’s-who of the jQuery world so you can be sure to get awesome presentations during the event. Lined up are experts like:

  • John Resig
  • Jonathan Snook
  • Richard Worth
  • Emily Lewis
  • …and a lot more.

The event is divided into two tracks targeting designers on the 16th and developers on the 17th. I’ll be presenting on the 17th and will be discussing how to use the new jQuery Templates plugin to make code layout much easier.

You can register for the event by going to the jQuery Summit website and when you do, be sure to take advantage of the following code for a 20% discount on your registration: JQUERY2010

The great thing about this is by registering, you’re also helping out the jQuery project as Environments for Humans is donating part of the proceeds of the conference to the jQuery Foundation.

I’m looking forward to this event and I hope to see you there as well!

How Polyfills “fill in the gaps” to make HTML5 and CSS3 Usable Today

There’s been a lot of commotion over the last week since the W3C announced that HTML5 is not ready yet for deployment to websites. Some really smart people have weighed in on this topic and I agree with their thoughts. Last Thursday, I did a presentation on the new features of HTML5 and part of that was demonstrating how polyfills work to allow you to leverage these new features while still providing a good cross-browser experience.

What’s a Polyfill?

I really love Paul Irish’s definition since it sums it up perfectly:

polyfill: A shim that mimics a future API, providing fallback functionality to older browsers.

The basic premise is that most older browsers may not have all of the features of the HTML5 and CSS3 specifications and they need a helping hand to make them provide a good user experience. A great example of this are the new HTML5 semantic tags like <article>, <section>, <header> & <nav> which render fine in all major modern browsers like IE9 beta, Firefox, Chrome, Safari & Opera but lack support in popular browsers like IE6 through IE8.

So for my demo, I decided to create a simple page that showed a blog-like layout using these new tags while ensuring that they can still render correctly in IE8. Here’s the layout code I used.

<!doctype html>
<html lang="en">
    <meta charset="utf-8" />
    <title>Rey's Awesome HTML5 Blog</title>
    <meta name="description" content="" />
    <meta name="keywords" content="" />
    <meta name="author" content="" />
    <meta name="viewport" content="width=device-width; initial-scale=1.0" />
    <!-- !CSS -->
    <link href="css/html5reset.css" rel="stylesheet" />
    <link href="css/style.css" rel="stylesheet" />
        <h1>Rey's Awesome HTML5 Blog</h1>

			<li><a href="#">Home</a></li>
			<li><a href="#">About</a></li>
			<li><a href="#">Contact</a></li>

        <h1>Rey's Blog Posts</h1>

            <header><h1>The In's & Out's of HTML5</h1></header>
		    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing  elit. Fusce vitae orci. </p>

                October 7, 2010 - comments( 0 )

            <header><h1>HTML5 Ate My Lunch</h1></header>
		    <p>Fusce vitae orci. Lorem ipsum dolor sit amet, consectetuer adipiscing  elit. </p>
                October 5, 2010 - comments( 3 )

		<p>Copyright Rey Bango, 2010</p>


I used a HTML5 reset style sheet because unfortunately, most browser don’t have an internal style sheet that sets the expected behavior for specific elements. For example, you would expect an <section> element to be block level but due to a lack of the internal browser style sheet, it renders inline.

Then, I added the styles I needed to get my page to look the way I wanted:

/* Global */
body { font-size: 16px; font-family: arial,helvetica,clean,sans-serif;  }
a { color : #33CC33; } 
a:hover { text-decoration: none; }

/* Header */
header h1 { font-size: 48px; }

nav { overflow: auto; margin-bottom: 25px; }
nav li {float:left; padding-right: 5px; }

/* Main Content Area */
section { width: 500px; font-size: 12px; }
section h1 { font-size: 16px; }

article { background: #CCCC99; margin-bottom: 10px; padding: 5px; -moz-border-radius:10px; -webkit-border-radius:10px; border-radius:10px; }
article footer { text-align: right; margin-right:5px; } 
article h1 { font-size: 12px; }

and when I tested it in Firefox 3.6.10, it looked exactly like I expected:

but look what happened when I tried to bring up the page in IE8:

None of the stylings were available because IE8 doesn’t recognize the new HTML5 elements. Further, in order to get IE6-8 to recognize these elements, you explicitly have to create the DOM nodes for them using JavaScript. The exact reason is unclear but it may be some type of parser bug. The following code needs to be in the <head> section of your page in order for the elements to be created and recognized by IE6-8:


It’s a little bothersome to do that but it’s not a massive bit of code at least.

Enter Modernizr

The code I just listed to create your HTML5 elements is certainly useful but work has already been done to handle that for us via the awesome Modernizr JavaScript library. Not only does it act as a polyfill, creating these new elements for us automatically, but it offers a ton of detection capabilities for features of both HTML5 & CSS3. This allows you to determine how you will offer fallback support when a feature isn’t available.

Including Modernizr.js is incredibly easy since it’s only a one line script tag like this:

<script src="js/modernizr-1.5.min.js"></script>

As I mentioned, Modernizr is smart enough to determine when new semantic elements need to be created and will handle the dynamic creation of elements such as <article>, <section>, <header> & <nav> instead of you having to write JavaScript code to do it. So once I’ve added Modernizr to my page, I get the following results in IE8:

Now you’re probably looking at this screenshot and say, “Hey, you have no rounded corners!”. You’re right because I used the CSS3 border-radius property to create rounder corners for all of my <article> elements and IE8 doesn’t support that property. The important thing, though, is that IE8 now recognizes these new elements and allowed me to style them.

But What About those Rounder Corners?

Geez, you guys are so demanding! Okay, so the cool thing is that Modernizr offers detection of key features of HTML5 *and* CSS3 and with that, we can determine if something like border-radius is available and if not, using a new term coined by Alex Sexton, we’ll use “regressive enhancement” to provide similar capabilities for older browsers. In this case, we’re going to see if border-radius is available and if not, lazyload in Mike Aslup’s jQuery Corners plugin to fill in the gap:

    <!-- Load jQuery -->
    <script src="" type="text/javascript"></script>
    <script type="text/javascript">
        // See if border-radius is available 
        if (!Modernizr.borderradius) {

            // If not, then load in the jQuery Corners plugin and apply rounded corners to the article elements
            $.getScript("js/jquery.corner.js", function () {


Now, when the code detects that border-radius is not available, it will just use the Corners jQuery plugin instead and render the following in any browser that doesn’t support the property:

Download the Code

I hope this post has shown you how polyfills can allow you to use HTML5 & CSS3 today. While I respect the W3C’s desire to ensure that the HTML5 specification is up-to-snuff, I think it’s important to realize that developers are resourceful and professional enough to create best practices that allow us to build apps with these new features right now.

I would highly recommend reviewing this VERY BIG LIST of polyfills and shims which can provide much of the missing capabilities in older browsers.

If you’d like to play with the code directly, I’ve packaged it up in a .zip file and you can download it here:

Code for HTML5 Semantic Tags using Polyfill to Degrade Gracefully (.zip)

How to Create HTML5 Website and Page Templates for Visual Studio 2010

Now that I work at Microsoft, I’m using Visual Studio 2010 as my main editor. By default, an empty web page is created with an XHTML 1.0 doctype and it’s pretty barebones. Since I’m focusing on HTML5 & JavaScript development, having to constantly update the page with references to the new HTML5 doctype, jQuery, Modernizr and all of the other tags I use for my pages was becoming a drag.

Today, I noticed a blog post by Zander Martineau in which he added a lot of HTML5 goodness to the Coda IDE in the form of clips, which is the code snippet format supported by Coda. This got me inspired to find out how to do something similar in Visual Studio, so I pinged Damian Edwards of the Visual Studio team for advice. He pointed me to the following article which explained how to create “Item Templates” in Visual Stuido.

The gist of it is that you can take any page that you create and turn it into a re-usable template via the “File->Export Template…” wizard. It walks you through the process of choosing a specific file or entire project/website to use as a template.

Adding a Page Template

So here’s the basic HTML5 template I wanted to include:

<!doctype html>   
<html lang="en">
	<meta charset="utf-8" />
	<meta name="description" content="" />
	<meta name="keywords" content="" />
	<meta name="author" content="" />
	<meta name="viewport" content="width=device-width; initial-scale=1.0" />
    <!-- !CSS -->
    <link href="css/html5reset.css" rel="stylesheet" />
    <link href="css/style.css" rel="stylesheet" />
    <!-- !Modernizr - All other JS at bottom 
	<script src="js/modernizr-1.5.min.js"></script> -->

	<!-- Grab Microsoft's or Google's CDN'd jQuery. fall back to local if necessary -->
    <!-- <script src="" type="text/javascript"></script> -->
	<!-- <script src=""></script> -->
	<script>	    !window.jQuery && document.write('<script src="js/jquery-1.4.2.min.js"><\/script>')</script>


	<div id="container">



After I created and saved this page, I went to “File->Export Template…” and followed these steps:

Now, when I select “File->New File…” to add a new item, my template is available:

Adding a Web Site Template

Creating this page template was a huge help. I can now start with a fresh template that specifically works for my style of development but I didn’t want to stop there. I also wanted to create a skeleton that I could use as the basis for new websites and I wanted it to package all of the important files that I use from the get-go. In this case, I wanted:

  • My HTML5 basic page template
  • jQuery
  • Modernizr
  • HTML5 Reset CSS file
  • An empty CSS file called style.css
  • A consistent folder structure for all of these

The first thing I needed to do was to create a new website in Visual Studio. From there, I needed to create and/or organize all of the files that I wanted as the basis for my skeleton. Using the same Export Template wizard, I followed the following steps to create my project skeleton:

So now when I select “File=>New Web Site” I see my new template:

and when I choose that, here’s what gets loaded for my new site:

Download the Templates

Note: The templates in this article have been updated to support jQuery 1.5.1 & Modernizr 1.7. Check it out here.

This is a huge time-saver for me and I want to share this. I’ve made both templates available for download so you can drop them into Visual Studio yourself. Just grab the specific file and drop the zip into the folder I specified:

HTML5 Page Template

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

HTML5 Web Site Template

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

Start Using CSS3 Pseudo-Classes in Internet Explorer 6, 7, and 8 using the Selectivizr JavaScript Library

Now that everyone is all giddy about CSS3 and all of the coolness it offers, lets get back down to earth. We still have older browsers to support so while using some of the new nifty features is definitely cool, we need to ensure we understand that at least 80% of web users won’t be on a cool new browser.

Enter Selectivizr, the Library Formerly Known as ie-css3.js

Internet Explorer is definitely one of those that needs special attention which is where a new library called Selectivizr comes in. It’s a JavaScript library that allows you to take advantage of CSS3 selectors now, even for users of Internet Explorer 6 through 8, by emulating these pseudo-selectors via JavaScript. It’s become such a hit that it was even nominated for Innovation of the Year in .net magazine’s 2010 awards.

The inclusion of Selectivizr is extremely easy. You add it in using a standard script tag just like any other JavaScript file. Notice that we’re using IE conditional statements to determine the browser version and if it’s less than IE9, the library gets included. Makes sense since IE9 should include many of these pseudo-selectors.

<script src="jquery-1.4.2.min.js"></script>
<!--[if lt IE 9]>
	<script src="selectivizr.js"></script>
	<noscript><link rel="stylesheet" href="css/ie-fallback.css" media="screen, projection"></noscript>
<link href="style.css" rel="stylesheet"> 

Once included, you’re now free to add CSS3 pseudo-classes to your style sheet. For example, I can now use the nth-child() pseudo-class to set the text to every odd numbered paragraph within my container div to red:

#container p:nth-child(odd) { color: #ff0000; }

and it will render correctly in Internet Explorer versions 6-8.

Check it out in Internet Explorer with Selectivizr NOT included.
Check it out in Internet Explorer with Selectivizr included.

In order to have done this previously, I would’ve have to had to rely on complex JavaScript or using methods included in a JavaScript library (e.g. jQuery’s nth-child method) to be able to grab the DOM element and style it. For example:

        $(document).ready(function () {

            $("#container p:nth-child(odd)").css("color", "#ff0000");


Check out the jQuery version in Internet Explorer with Selectivizr NOT included.

While that will style the paragraphs the way I want, it’s not a portable and reusable solution. Using Selectivizr is substantially easier because I can now specify reusable CSS rules where they belong; in a style sheet.

The main thing that you NEED to have is a JavaScript library with a DOM selector engine. Selectivizr has support for jQuery, MooTools, Dojo, Prototype, YUI, DOMAssistant and the NWMatcher selector engine. Considering that most sites leverage at least one of these libs, that’s pretty good coverage.

One of the things I did notice when doing a view source on the Selectivizr website is something that I had already thought would be a good idea. The author, Keith Clark, combines his Selectivizr code with Remy Sharp’s html5shiv which makes a lot of sense considering html5shiv allows you style HTML5 tags in non-supporting browsers. So rolling up these two libs (or Modernizr) is a good idea. One less http request to make.

How Does this Work?

I pinged Keith so I can get a better understanding of the magic going on under the hood and here’s what he said:

Basically, the script scans the page looking for <link>‘d style sheets which are downloaded using a XmlHttpRequest (or ActiveX for IE6). The style sheets are then parsed for rules containing CSS3 selectors. Any matching rules are extracted and passed to a JavaScript library (such as jQuery, Prototype, NWMatcher etc.) which selects matching elements from the page. These elements are then given a unique className and, if necessary, event handlers are added (if interactive pseudo-classes such as :hover, :focus, : checked etc. need to be emulated). The original CSS rule is then replaced with the same className and once all rules are processed, the original style sheet content is replaced with the modified one.

So if you’re wondering why there’s a dependency on a JS lib, there ya go. For a deeper dive into the how-to’s check out his more thorough explanation here.

How to Easily Inject jQuery into any Web Page

I use jQuery…a lot. It just makes JavaScript development much easier for me. Every so often, I may come across a site where I want to poke around and see what’s going on under the hood. In many cases, jQuery is being used so it’s simple to spark up Firebug and leverage jQuery to work with a document. While jQuery is very pervasive, there are still plenty of sites that don’t use it which forces me to go back to plain ‘ole JavaScript. There’s nothing wrong with that but I’ve gotten used to the nice, terse syntax jQuery provides and I’d like to be able to use it.

Awhile back, I came across an awesome bookmarklet created by my jQuery teammate, Karl Swedberg, which allows me to inject the latest version of jQuery right into my page. This is great when you want to work with a page which doesn’t have jQuery included and you either don’t own the page or don’t feel like adding a script tag to it. The code below shows how the jQuery lib is included.

It’s fairly straightforward in that a script element is created:

var script=document.createElement('script');

and the script tag’s src attribute is set with the following URL:


Then, they grab a reference to the document’s head DOM element:

var head=document.getElementsByTagName('head')[0]...;

and then insert the new script tag into the head of the document.


That was a very high-level explanation because there’s definitely more going on. In fact, Karl took the extra step of ensuring that jQuery’s .noConflict() method is called should there be another library present that requires the “$” namespace. Very cool. :)

Now, this leverages the latest minified version from the jQuery repo but you should be able to easily include a version of jQuery from the Microsoft or Google CDNs if that’s your preference:


You can find the full source for the bookmarklet below and if you want to install it now, here’s the link for you to use:

» jQuerify «– Drag this link to your browser toolbar

I created a quick screencast that shows you how to add the bookmarklet to your browser and then use it for playing with a web page:

Nicely formatted bookmarklet code:

(function() {
  var el=document.createElement('div'),
   msg='';'fixed';'32px';'220px';'-110px';'0';'50%';'5px 10px'; = 1001;'12px';'#222';'#f99';
  if(typeof jQuery!='undefined') {
 msg='This page already using jQuery v'+jQuery.fn.jquery;
 return showMsg();
  } else if (typeof $=='function') {
  // more or less stolen form jquery core and adapted by paul irish
  function getScript(url,success){
 var script=document.createElement('script');
 var head=document.getElementsByTagName('head')[0],
 // Attach handlers for all browsers
 script.onload=script.onreadystatechange = function(){
   if ( !done && (!this.readyState
     || this.readyState == 'loaded'
     || this.readyState == 'complete') ) {
  script.onload = script.onreadystatechange = null;
  getScript('',function() {
 if (typeof jQuery=='undefined') {
   msg='Sorry, but jQuery wasn\'t able to load';
 } else {
   msg='This page is now jQuerified with v' + jQuery.fn.jquery;
   if (otherlib) {msg+=' and noConflict(). Use $jq(), not $().';}
 return showMsg();
  function showMsg() {
 window.setTimeout(function() {
   if (typeof jQuery=='undefined') {
   } else {
  jQuery(el).fadeOut('slow',function() {
  if (otherlib) {
 } ,2500);

The Case for jQuery’s .delegate() Method for Dynamic Event Binding

Binding events is one of the most common tasks a JavaScript developer has to do. It’s integral to the way our applications handle user interaction and response. Since it’s inception, jQuery has had event handling via various helper methods that helped to abstract cross-browser differences. If you’re a jQuery developer, I’m sure you’re used to syntax like this:

$("#clname").click( function() { alert( "Rey" ) } );

which would bind a click event to a DOM element with an ID of “clname”. Very easy to understanding and simple to use. But when you get past just simple use of JavaScript and start inserting new DOM nodes, this binding becomes less useful because it can’t handle dynamically inserted elements. Let me explain.

Say you have the following HTML markup:

<div id="clcontainer">
<a href="#" class="clients">Click for Rey Information</a>

and you bind the click event to generate an alert of some type like this:

$(".clients").click( function() { alert( "Here's some information." ) } );

but then you decide that you’re going to add a new DOM element to the page dynamically:

$("#clcontainer" ).append( "<a href='#' class='clients'>Click for Mark Information</a>" )

What do you think will happen? I would venture many developers might expect that the second, dynamically appended DOM element would share the same binding as the first since they share the same class name. That’s not the case. jQuery methods such as click(), dbclick(), and bind() are meant to bind events to a specific set of available DOM elements (i.e: not dynamically appended). (Note: I updated this part to better clarify what I meant based on feedback by Jamie Newman)

Now to get around this limitation, jQuery team member Brandon Aaron initially created a plugin called LiveQuery which would allow you to bind events not only to specific DOM elements but all subsequent DOM elements that were appended to the DOM that matched the selector specified in the initial binding. That plugin eventually became part of the jQuery Core library and renamed simply to live(). The great thing with live() is that you could now bind dynamically added DOM elements like this:

$(".clients").live( "click", function() { alert( "Here's some information." ) } );

and if you did append a new DOM element, like this:

$("#clcontainer" ).append( "<a href='#' class='clients'>Click for Mark Information</a>" )

it would now share the same function binding as initially defined.

The Problem with Live()

Now, live() is an awesome method and people totally loved it. That is, until they wanted to bind events based on a deeper DOM traversal than just a single element, specifically when methods were used that alter the selector expression’s initial results (e.g.: using children()). So, if we had markup like this:

<div id="clcontainer">

and tried to use live() to bind all of the list items like this:

$("#clcontainer").children( "ul" ).find( "li" ).live( "click", function() { alert( "Here's some information." ) } );

the binding would fail. Since chaining is so widely used within the jQuery community, this was a bit of a surprise to many and one of the most requested updates to jQuery.

In order to get around this, Brandon introduced in jQuery v 1.4 the new delegate() method. It provides greater control by allowing you to specify the context to which you’d like to bind to. So using the same example as above and making some slight changes to use delegate(), we’re now able to use chaining to determine our selector results and then specify that we’d like all current and future list items to be bound to our declared function:

$("#clcontainer").children( "ul" ).delegate( "li", "click", function() { alert( "Here's some information." ) } );	

When to Use live() or delegate()

These two convenience methods are totally awesome and incredibly helpful with more complex apps. The best use case for them is when you know that you will be dynamically adding new DOM elements and they’ll share the same bound function. I mean, essentially that’s the premise of event delegation. You’re trying to limit the number of event handlers needed to handle functionality and increase maintainability be centralizing your logic. Make sense. If you’re not going to be doing anything that involved, though, then jQuery’s event helper methods such as bind(), click() etc. are still excellent choices for those one-off scenarios.

The Essential List of JavaScript, jQuery, HTML & CSS Books to Make You a Better Web Developer

Over the years, I’ve read or been recommended a number of books which are essential reading for professional web developers. I’ve compiled the list of books below to help the community find a comprehensive list of good books that can help them be better coders.


Professional JavaScript for Web Developers – My new favorite book. Almost 1,000 pages of VERY detailed JavaScript information. Written by Nicholas Zakas, Yahoo! Principal Front-end Engineer for Yahoo!’s home page and recommended by the YUI team as well. BUY THIS BOOK!

JavaScript: The Definitive Guide – Considered the Bible of JavaScript for its thorough coverage of JavaScript. You need to have this in your library, even as a reference.

DOM Scripting: Web Design with JavaScript and the Document Object Model – This is a good book to get you familiar with the DOM.

AdvancED DOM Scripting: Dynamic Web Design Techniques

Beginning JavaScript with DOM Scripting and Ajax: From Novice to Professional – The book by Christian Heilmann that really got me past the initial hump of plain ‘ole JavaScript. His writing style is awesome.

Object-Oriented JavaScript: Create scalable, reusable high-quality JavaScript applications and libraries – JUST BUY THIS BOOK! Stoyan did a great job of outlining OOJS principles and it’s been incredibly valuable.

JavaScript: The Good Parts – It’s certainly a good book and I would recommend reading it after one of the more intro books like JS for Web Developer by Nicholas Zakas.

Learning jQuery 1.3 – While covering jQuery v1.3, the techniques discussed are still useful and I still recommend the book highly.

Pro JavaScript Techniques – John Resig’s famous book on advanced JS techniques.

Secrets of the JavaScript Ninja – Still not out but considering that John Resig is that author, it’s sure to be great.

ppk on JavaScript, 1/e – One of the first books I picked up and great overview of the language.

Accelerated DOM Scripting with Ajax, APIs, and Libraries

Ajax Security – Billy Hoffman is the man when it comes to Ajax security and this books shows why.

jQuery Cookbook: Solutions & Examples for jQuery Developers (Animal Guide) – Tips & techniques from the jQuery team rolled up in a cookbook style. You can’t go wrong.

jQuery in Action, Second Edition – This is now updated for jQuery v1.4.x as well as jQuery UI 1.8.x. Definitely a must-have for jQuery developers

jQuery Enlightenment – Cody Lindley did an amazing job in outlining the best jQuery techniques in this self-published book. Totally worth the price.

Test-Driven JavaScript Development

jQuery: Novice to Ninja


Web Standards Solutions: The Markup and Style Handbook, Special Edition

Bulletproof Web Design: Improving flexibility and protecting against worst-case scenarios with XHTML and CSS (2nd Edition)

The Art & Science Of CSS – This is one of Sitepoint’s best CSS books. Loved it.

HTML Utopia: Designing Without Tables Using CSS, 2nd Edition – Not being a designer, I thought this book was a tremendous help in understanding how to better design sites.

Head First HTML with CSS & XHTML – This has been my goto book for some time. The Head First books are just so great at breaking down topics in easy to understand ways and this book is no exception.

Introducing HTML5 (Voices That Matter) – Going to get this soon mainly because it’s written by Remy Sharp and Bruce Lawson whom I respect tremendously, especially for their HTML5 & CSS3 savvy.

HTML5 For Web Designers – Just got this on 7/19/10. Need to read it by it’s by Jeremy Keith and he rocks.

CSS Cookbook, 3rd Edition (Animal Guide) – Just picked this up on a recommendation.

CSS: The Missing Manual – I keep hearing rave reviews about this book all over the place.

Site Performance & Enhancement

High Performance Web Sites: Essential Knowledge for Front-End Engineers – Steve Souders is the performance guru and if you want your apps to perform better, get this book and the one right below this one.

Even Faster Web Sites: Performance Best Practices for Web Developers

High Performance JavaScript (Build Faster Web Application Interfaces) – Again, another great book by Nicholas Zakas which outlines very important performance techniques for JavaScript applications.

Designing with Progressive Enhancement: Building the Web that Works for Everyone – Great book on progressive enhancement by the superstars at the Filament Group.

This is certainly not all inclusive and I’m sure there are other books out there that have been great. If you feel very passionate about a specific title, let me know via the comments and I’ll check it out.

jQuery JavaScript Templates Tutorial: Inline Expressions and Code Blocks

So far in my series on jQuery JavaScript Templating, I’ve showed how to create a basic jQuery JavaScript template and then nest templates for increased layout flexibility and maintainability. If you haven’t read those two posts, I highly recommend you do so you can understand the concepts below.

Now, let’s dive into two other techniques available in the Microsoft jQuery Templates plugin; inline expressions and code blocks.

Inline Expressions

Being able to use a template to create a succinct layout is very powerful but without the ability to manipulate the data that’s being rendered, you’d probably find templates a lot less useful. That’s where inline expressions come in. Inline expressions allow you to use common JavaScript expressions to effect a change in the way your data is rendered. Using a slightly modified version of the data from my last tutorial, I can show you what I mean. Here’s the data:

var clientData = [
     { first: "Rey", last: "Bango", age: 42, id: 1, phone: [ "954-600-1234", "954-355-5555" ] },
     { first: "Mark", last: "Goldberg", age: 51, id: 2, phone: ["954-600-1234", "954-355-5555"] },
     { first: "Jen", last: "Statford", age: "25", id: 3, phone: ["954-600-1234", "954-355-5555"] }

What I did was break out the “name” attribute into “first” and “last” name fields. Now, say I wanted to render the full name in my template. I would use the following inline expression to do so:

<script id="clientTemplate" type="text/html">
    <p><li>${ first + " " + last }</li></p>

Which gives me the following result:

Notice that I’m using the standard JavaScript “+” operator to concatenate the two data attributes together to form my final output. JavaScript developers should immediately be able to understand the code here and see how flexible this option is.

Code Blocks

Now, while inline expressions are certainly powerful, the ability to affect the data via code blocks is even more important because it allows you to specify conditional statements that can be used to determine what type of and when data will be represented. Let’s say that based on the age of a client, I want to show some text next to their name. I’ll use the following code block:

{{if (age > 30)}}veteran coder!{{else}}rising star!{{/if}}

This code block allows me to specify a conditional statement that allows me to create a nice descriptor based on the person’s age. The key is the “{{if..else}}” custom tag that’s been incorporated into the template plugin that allows you to specify conditional statements.

Here’s what the template would look like:

<script id="clientTemplate" type="text/html">
    <p><li>${ first + " " + last + " is a " }{{if (age > 30)}}veteran coder!{{else}}rising star!{{/if}}</li> </p>

which generates the following results:

And again, the cool thing is that the syntax for the expressions use standard JavaScript operators so I can do something like this as well:

{{if (age > 20 && age < 30 || age == 42)}}rising star!{{else}}veteran coder!{{/if}}

The thing to stress here is that using inline expressions and code blocks together can give you a tremendous amount of control over how you control you data. You have the flexibility you’d expect by using JavaScript but in a manner that is easily readable and maintainable.

Here’s the final code:

<!DOCTYPE html>
<html lang="en">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="robots" content="noindex" />
  <title>Template Test</title>
  <script src="" type="text/javascript"></script>
  <script src="jquery.tmpl.js" type="text/javascript"></script>
  <script type="text/javascript">
  $(document).ready(function() {
var clientData = [
     { first: "Rey", last: "Bango", age: 42, id: 1, phone: [ "954-600-1234", "954-355-5555" ] },
     { first: "Mark", last: "Goldberg", age: 51, id: 2, phone: ["954-600-1234", "954-355-5555"] },
     { first: "Jen", last: "Statford", age: "25", id: 3, phone: ["954-600-1234", "954-355-5555"] }
<script id="clientTemplate" type="text/html">
    <p><li>${ first + " " + last + " is a " }{{if (age > 20 && age < 30 || age == 42)}}rising star!{{else}}veteran coder!{{/if}}</li> </p>

The Source Code for my Twitter Demo from the Think Vitamin jQuery Online Conference Templating Presentation

I just finished my presentation at Think Vitamin’s jQuery Online Conference and it was such a great experience. This is the first BIG virtual conference I’ve presented at and it ran smooth as silk. I really have to hand it to the Carsonified team; they have their act together. :)

The big takeaways:

  • Online conferences rock! No travel == less expenses.
  • The technology is good enough to be able to do this and WebEx is awesome.
  • Carsonified’s got this down. While some tech problems are expected, they’ve really got the process working well.

The only downside, from a speaker perspective, is that you really can’t see how your audience is reacting. That’s tough because sometimes, you’re able to adjust according to your audience’s feedback. If there’s dead silence, you know you need to bring them back. If they’re engaged, you know you’re on track. In a virtual conference, you can’t gauge that so it’s tough.

Lots of folks have asked for the code for the Twitter demo that I did. You can now download that below:

Download the Twitter Demo Source

I want to thank everyone for attending and for the kind words. I really appreciate it. I also want to thank Carsonified for giving me the opportunity to speak at a great event.

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!


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