If you haven't started using HTML5 or would like some help to make the learning curve easier, you're in luck. Many libraries and tools are available. Of course, HTML5 encompasses so many APIs, elements, and Cascading Style Sheets 3 (CSS3), that it helps knowing where to start. While you can write JavaScript directly against the new HTML5 APIs, it often helps to have some level of abstraction. CSS3 also adds new and sometimes confusing rendering functionality to the web, and good references and examples clear the confusion.

This article comprises my top 10 go-to libraries and tools for building the most modern HTML5 and CSS3 web projects such as websites, mobile websites, and applications. I'm sure you'll find them as useful as I do; beginning with what is undoubtedly my favorite, and should be the base template from which all web projects are created.

HTML5 Boilerplate

The nature of web architecture has changed drastically in the past four to five years. Application structure, page structure, and base resources matter more than ever before. Keeping up with the latest changes across all browsers, libraries, and techniques can be difficult even for the most connected developer. Fortunately, the HTML5 Boilerplate project alleviates many of those concerns.

The open-source Boilerplate project for HTML5 web development templates on GitHub is the best place to start for modern web application development. It's a set of front-end templates that let you create HTML5 web pages with ease. Boilerplate begins with website structure (Figure 1). Files and folders representing a base structure are organized properly and easily customized. There are folders for CSS, scripts, documentation, and images and core files for markup (index.html), 404, crossdomain.xml, robots.txt, humans.txt, favicon icons, and Apple Touch icons. Many developers still don't include some functionality, such as humans.txt and Apple Touch icons, in their website projects; however, these files and folders are important because they represent a minimal, modern website. I have increased my own understanding of modern web development and found answers to nagging questions just by evaluating HTML5 Boilerplate code.

Figure 1: HTML5 Boilerplate project structure

HTML. Properly structuring a modern, HTML5 web page is simple, yet many developers seem to be confused by it. This is one of the reasons why HTML5 Boilerplate is so important. The index.html file (Figure 1) serves as the perfect reference for how you should mark up a basic HTML5 layout. The head element contains a minimum set of markup for including a page description, forcing the latest version of Internet Explorer (IE), and referencing the site's CSS and Modernizr script—more on that later.

The index.html page template's body includes some placeholder text and an example of how to nicely prompt the user to upgrade from IE 6.0. Below the page content are scripts. The body ends with the code (all except your site ID) that implements Google Analytics. Reviewing this latest Boilerplate template, I find it funny the HTML5 Boilerplate markup doesn't seem to contain any HTML5-specific tags.

CSS. The Boilerplate's core CSS folder contains two files: the main.css starter style sheet and the normalize.css cascading style sheet. The normalize.css file is a CSS reset style that, in case you are not aware, levels the field among browsers so all elements have a common set of styles applied to them. The main.css style sheet includes styles that improve readability, correct alignment issues, and eliminate common styling problems such as unwanted text shadows. It also includes helper classes that assist in providing hidden element, media query, and print style functionality.

JavaScript. The Boilerplate's js folder contains placeholder files for your website's JavaScript. The vendor folder contains the latest jQuery and Modernizr files. The js folder is minimal, and if you dig into good JavaScript project organization, you'll discover it can get rather complex. But like I said, the Boilerplate project is a good place to start.

Web server. There is also an .htaccess file for optimizing Apache server configuration, which may not be useful to ASP.NET developers like me. Fortunately, there is another Boilerplate project that contains web server configuration templates—among them a rich, Microsoft Internet Information Services 7.0 (IIS 7) web.config file—for ASP.NET developers.

Mobile Boilerplate

There also is an HTML5 Mobile Boilerplate template project that provides a solid foundation for creating smartphone websites or web applications. The Mobile Boilerplate project contains the same features as its desktop sibling, plus features specific to smartphone browsers. The additional features include meta tags for iOS web apps, Windows 8 live tiles, and a library that prompts the user to add the web app icon to a home screen for future use. Again, review the project's documentation to learn more.

HTML5 Boilerplate is the absolute best place to go when you begin a modern web development project because it provides a solid project structure, files, and example code to get you started on the right foot. It is maintained by a talented group of web developers and routinely updated to support the latest web development best practices, so you can spend more time on your web applications.

Modernizr

In the past, web developers incorporated browser detection in their websites by employing user-agent strings to determine what a browser could and could not do. When using browser detection you would load an IE 6.0 style sheet or maybe a JavaScript file to accomplish layout and client-side functionality. But with the proliferation of browser and platform combinations, this has proven far too complicated and unreliable. Instead, the best practice has become feature detection, and no library is better at providing this functionality than Modernizr (modernizr.com). It provides a battery of tests to determine whether various HTML5 and CSS3 features and APIs are supported by a browser.

Using the Modernizr library is extremely easy. First, download the library from modernizr.com or from its GitHub repository. Then add it to your web page (see the index.html file referenced above in the HTML5 Boilerplate project for an example). The Modernizr script should be the only script reference in your document's head element because it performs the feature detection test to determine what the browser can and cannot do.

Modernizr also updates older browsers to allow styling for new HTML5 elements by creating each new HTML5 semantic element. This is a little trick many HTML5 shims perform because older browsers will not style the first instance of an unknown element, but will style later instances.

Feature detection. To test whether a specific HTML5 or CSS3 property is supported, you simply access the corresponding Modernizr object's property. For example, to check whether a browser supports the GeoLocation API, you would write a JavaScript If... Else statement similar to that in Listing 1.

if(Modernizr.geolocation){
     //execute your geolocation functionality here
}else{
     //deal with no geo support
}

There are many HTML5 and CSS3 features that Modernizr detects.

Polyfill libraries. While Modernizr is great for feature detection and providing some backward compatibility support in older versions of IE, the library isn't a polyfill library. Polyfills are typically JavaScript libraries that implement new HTML5 and CSS3 functionality in older browsers. If you need such backward compatibility, check out the GitHub page that lists polyfills for just about every modern web feature.

You can use Modernizr as the tool to load polyfill libraries. Modernizr includes the yepnope.js library to make loading polyfills simple. Modernizr has a load method that passes a JavaScript object with features and scripts, depending on whether a feature is supported. Listing 2 is an example from the yepnope documentation for loading a geolocation polyfill.

Modernizr.load({
  test: Modernizr.geolocation,
  yep : 'geo.js',
  nope: 'geo-polyfill.js'
});

If you want to see which modern features your browser supports, visit a site such as Haz.io, which uses Modernizr to list HTML, CSS, and JavaScript features a browser does and doesn't support.

localStorage

The localStorage API is one of my favorite HTML5 resources. localStorage provides 5MB of string-based storage to each domain within the browser's context, or that is accessible by the browser. It's easy to work with, but I find it helpful (and better for data management) to use the API in a localStorage abstraction library. Two of these libraries include lawnchair, and lscache. But I recently found a little jQuery AJAX preFilter created by Paul Irish to cache AJAX data. If you aren't familiar with jQuery AJAX preFilters, they were added in jQuery version 1.5. They are a low-level API that lets you hook into the AJAX pipeline and modify a request.

Listing 3 shows an example of a jQuery AJAX call that adds localStorage caching properties to a website. The localStorage cache prefilter first checks to see if the data being requested already exists in localStorage. If so, it returns that value and cancels the AJAX call. If the data doesn't exist, the prefilter permits the request and caches the data upon a successful result.

$.ajax({
        url          : '/post',
        localCache   : true,        // required to use

        cacheTTL     : 1,           // in hours. Optional
        cacheKey     : 'post',      // optional
        isCacheValid : function(){  // optional
            return true;
        },

        success: function(reply) {
            // i can play with my reply !
        }
    });

Data is stored using a timeout value so it won't get stale. If the prefilter checks for the data's existence and finds it's past its expiration, the prefilter will purge the data from localStorage and perform a new AJAX request.

The localStorage prefilter is a great, unobtrusive way to speed up your app's performance. One thing I will warn you about, though, is the deferred or promise pattern: a new, chainable pattern used for callbacks. I've encountered problems working with promises and the localStorage prefilter, so my advice is to use a traditional success callback instead.

Canvas

The HTML5 canvas tag is used to dynamically draw and manipulate graphics with JavaScript. Combined with its cousin, Scalable Vector Graphics (SVG), web developers can drive engaging experiences for games, charts, and many other multimedia functions. SVG is generally used for static graphics, while canvas is meant for more dynamic functions such as gaming. Because developers can use canvas for a variety of functions, there is not just one library I recommend, but several.

jCanvaScript. jCanvaScript is a nice library that makes it easy to create and animate shapes. The library is object oriented and includes built-in support for both mouse and keyboard events. I like it because it makes it easy to manage the animation process.

Fabric. Fabric.js (Figure 2) is similar to jCanvaScript but is more feature rich and has a higher learning curve. Fabric also provides an SVG-to-canvas parser. Fabric has features for color helpers, pre-IE 9.0 support, touch events, and manipulating images. It also offers a pretty decent gaming foundation. Fabricjs.com is rich with demos and documentation, which really helps with the learning curve of this expansive library.

Figure 2: Canvas object created using Fabric.js
Impact. If a game-centric canvas library is what you want, there are some decent free ones, but serious game developers should consider the $99 investment in Impact—it's worth it. The library is designed—first and foremost—for game development and to run across multiple browsers and platforms (Figure 3). The project has extensive documentation, video tutorials, and Jesse Freeman has written a book, Introducing HTML5 Game Development, on how to use the Impact JavaScript game engine. The impactjs.com website also offers forums and a blog to help answer developers' questions.

Figure 3: HTML5 canvas game created using Impact game engine

CSS3 Shapes

The days of squares, rectangles, and complicated image slicing is officially over. Not only can drop shadows, gradients, and rounded corners be accomplished through CSS, but so can complex shapes. The CSS3 Shapes library provides the CSS code (Figure 4) to make 20 unique and useful shapes with a single div element, including a heart, callout, stop sign, egg, and (of course) PacMan.

Figure 4: A static shape and its corresponding CSS code from CSS3 Shapes

The site begins with a simple circle and square and progresses to more complicated shapes until it finishes with a heart. CSS3 Shapes doesn't provide a source file to download, but the source code is available, smack dab in the middle of the page, beside each shape. I also found it fun and educational to load the page in Chrome and inspect each shape in developer tools, where I typically make adjustments in the CSS to see how they affect the shape. This gives me more hands-on knowledge about how the CSS3 rules affect an element.

Another aspect of CSS3 and HTML5 that the CSS3 Shapes examples exposed me to is the psuedo elements ::before and ::after. These are virtual elements that do not exist in HTML5 markup but are available to apply as styles, which is how several shapes are made.

CSS3 Animations

CSS3 has added the ability to animate Document Object Model (DOM) elements, but if you are like me, it isn't the easiest thing to master. Fortunately, Daniel Eden created Animate.css to make it easy to add CSS animations to a web page. In fact, the library's tag line is "Just-add-water CSS animation." Animate.css provides several dozen animations for easy-to-add interactive fun in your web applications.

The project's home page also serves as a demonstration of each animation (Figure 5). And if you can't find an animation to fit your needs, examine the CSS source to see how each one works and adapt it to your needs. I have found it an indispensable resource for learning and gaining a hands-on understanding of CSS animations. For example, I was really struggling with flipping elements, such as a playing card, but studying the code behind the flip animations helped immensely with my understanding.

Figure 5: Flipping an element using CSS animation on Animate.css

Examining the animations also will help you better understand how to leverage key-frame animations. Key-frame animations are a new CSS3 feature that lets you define how an element is styled over a period of time. In Listing 4 you can see how the shake animation is defined to run over one second. The key frame moves the element back and forth by 10 pixels every 100ms.

.animated {
     -webkit-animation-duration: 1s;
        -moz-animation-duration: 1s;
          -o-animation-duration: 1s;
             animation-duration: 1s;
     -webkit-animation-fill-mode: both;
        -moz-animation-fill-mode: both;
          -o-animation-fill-mode: both;
             animation-fill-mode: both;
}

@keyframes shake {
     0%, 100% {transform: translateX(0);}
     10%, 30%, 50%, 70%, 90% {transform: translateX(-10px);}
     20%, 40%, 60%, 80% {transform: translateX(10px);}
}

The animations on Animate.css are organized by types: attention seekers, flippers, fades, bounces, rotating, lighting, and specials. No matter what your needs are, the CSS animations library is sure to have something that can help you.

SignalR

WebSockets is an HTML5 API that's supported by all modern browsers. In the ASP.NET space there is nothing more popular for WebSockets than the SignalR Library. SignalR was created by Damien Edwards, David Fowl, and several other contributors on the ASP.NET team to abstract web socket support and provide built-in backward compatibility with older browsers.

SignalR provides for a dedicated channel or hubs. A dedicated channel is an isolated, "two-way pipe" between a client and server. A hub works as a proxy point to broadcast a message from a client to all subscribed clients. Think of it as a multi-person chat where you post a message and the other 10 subscribers immediately see your message.

SignalR is a complete WebSocket library. The library offers both a client-side JavaScript library (as a jQuery plug-in), as well as robust server-side support for various .NET server scenarios. The SignalR source code download on GitHub includes a broad set of examples that cover just about every implementation scenario you might need. The standard website library is an ASP.NET class you can use to derive your own end point. There are also client libraries for Silverlight, Windows Phone, and Windows RT applications. You'll also find server libraries for Open Web Interface for .NET (OWIN), Katana, Microsoft SQL Server in-memory technology, Windows Azure Service Bus, and a few others.

If you want to use a production SignalR site, visit JabbR (Figure 6), which is what I call a casual-support chat site. The site leverages SignalR to broadcast real-time requests to a variety of topic rooms. Registered users can view and add to conversations and questions about various developer topics.

DeepTissue

Developing an application without touch functionality in mind is almost a failing proposition. Consumers and enterprise workers are adopting tablets and smartphones at a rapid pace. More and more laptops include touch screens as a standard feature. This means the days of using the mouse as a primary pointing device are numbered. Touch is extremely important and not left out of the HTML5 umbrella.

Unfortunately, there are two competing standards, the WebKit Touch API from Apple, and the Microsoft IE Pointer API. Several touch libraries support only the WebKit Touch API, and a few libraries add value to the Pointer API, but none seem to support both. So I created the DeepTissue library to do just that.

The core goal of DeepTissue is to abstract the browser's support for either Microsoft Pointer, Apple Touch API or traditional mouse events, making it transparent to the developer what the browser supports. Instead of binding to touch, mouse, or pointer events, you create an instance of DeepTissue for the target DOM element and set up the appropriate action method, such as move (Figure 7), scale, or tap.

figure7_sm

The script in Listing 5 shows how to apply the DeepTissue library to an element and specify the callback. In this case the element moves by following the user's finger or mouse, whichever the case may be.

var dt = deeptissue(document.querySelectorAll(".move-target")),
          el = document.querySelector(".touch-log");
           
      dt.move(function (evt, m) {
           
          el.innerText = "move " +
                evt.translationX + "px " +
                evt.translationY + "px\n" +
                el.innerText;
           
      });

The DeepTissue library provides scripts for move, rotate, scale, tap, doubleTap, tapHold, and swiping, representing a core set of possible user actions for both single and double-touch points. In the future I hope to add even more multipoint gestures.

Vanilla JS

Eliminating JavaScript libraries such as jQuery is an up-and-coming trend nick-named Vanilla JS. Instead of using a library, you work directly against the browser's native APIs. This may sound scary at first, but it's fairly easy for those with a reasonable amount of JavaScript experience. Don't worry if you feel like a JavaScript newbie, we've all been there. Think of jQuery as a set of training wheels that helped you get comfortable programming JavaScript.

JavaScript libraries such as jQuery, Prototype, etc., were created to level the playing field between browsers and make traversing the DOM easier. This was very necessary five years ago because there were so many variations in the way browsers implemented native API calls, and the DOM selector API was limited compared to what we have today. The mass adoption of JavaScript libraries resulted in the rapid growth of rich, web client applications. Ultimately, this growth caused browser vendors to create native API calls that almost eliminate the need for large JavaScript libraries that abstract differences among browsers.

HTML5 is about having common standards across browsers so websites need only minimal abstractions provided by libraries. Today, almost every browser supports Document.querySelectorAll, which means you can pass in a CSS selector to retrieve a list of matching nodes just like you would using jQuery (Listing 6).

var $products = $(".products-list > .product-list-item");
var productNodes = document.querySelectorAll(".products-list > .product-list-item");
var $fasterProducts = $(document.querySelectorAll(".products-list > .product-list-item"));

The native call is orders of magnitude faster and can be passed directly to the $() object constructor. The following is a list of DOM Element Query Methods for Document.querySelctorAll:

  • document.getElementById
  • document.getElementsByClassName
  • document.getElementsByName
  • document.getElementsByTagName
  • document.querySelector
  • document.querySelectorAll

As legacy browsers such as IE 6.0 and 7.0 fade away, the need to worry about edge cases die with them. This is why the jQuery team is trimming the legacy fat from jQuery 2.0. Reducing this overhead will have a positive impact on your application's performance. Utility libraries such as Underscore can fill in the gaps you still need if you choose to eliminate larger libraries such as jQuery altogether.

Obtainable Functionality

HTML5 provides a richness we have only dreamed about. Not only does it offer many great new features, but HTML5 has helped standardize browser implementations and interfaces, making the developer's life easier. Having a good toolbox of HTML5 libraries, references, and knowledge helps even the newest developer create web experiences that were complicated—if not impossible—in the recent past. So whether it's HTML, CSS, or JavaScript, check out the multiple good—free and commercial—libraries for obtainable functionality. In the next article of this HTML5 series, we'll introduce you to writing basic HTML5 and jQuery code in "Three of the Most Important Basic Elements in HTML5."