Compass In Hand

Guiding The Geek In You

Monthly Archives: November 2013

How to Build a Project Sandbox

Sometimes the hardest part about a project is sitting down to organize your environment before you begin. Sure, you probably have several, maybe hundreds, of pieces of functional code stashed in your git repo or squirreled away in different folders on your hard drive, but starting a brand new project? Ugh! Enter the project sandbox.

Why a Project Sandbox?

Project sandboxes are templates designed for easy duplication that allow you to quickly create an ideal project environment. Pre-configured folder structures and file names optimized to your liking make launching a new project as easy as duplicating a template and making a tweak to the new project’s server config file.

Similar to regular sandboxes – also known as development servers – project sandboxes isolate projects to a well-defined structure, preventing code pollution. The key difference is Sandboxes are usually designed for developing within an existing code base protected by a code repository. Project sandboxes, however, exist only to help start new and potentially disposable development in a reliable way.

Naming schemes

Regarding naming schemes: the word of the day is CONSISTENCY. Name your project sandbox files anything you like and commit to your scheme. When you find a better naming method (and you will), retrofit your project sandbox right away – don’t put it off! Using consistent file names will build strong mental associations that help you decide where to put certain code.

My project sandbox files:

  • main.js
  • main.css
  • index.html

Some file stubs (files that exist without any content) I like keeping handy to handle RWD needs, or to load AMD formatted scripts, respectively:

  • responsive.css
  • requireLoader.js

Being Flexible

Flexibility in terms of a project sandbox means keeping a variety of battle tested and carefully vetted resources at your finger tips, not all of which you may need for every project. Some resources should be configured to load by default, while others (like frameworks) are kept out of the loading stack.

Some of my core resources:

General Tools

Asynchronous Resource Loaders

JS MVC Frameworks

JS Libraries

  • Underscore.js
  • jQuery (keep a couple of versions handy – load one by default)
  • Zepto.js (lighter weight than jQuery, better for mobile devices)
  • [Your Favorite jQuery Plug-ins Here]

CDN vs Locally Stored Resources

Should you use a CDN or keep your toolkit stored locally? I prefer using local files. Staying local removes a layer of potential complexity (not relying on a file that probably stays the same), improves performance, and keeps resource files readily available for dissection. That said, CDNs are extremely valuable in many other situations.

However, using local resources means you must manually keep your project sandbox current. Get into the habit of watching for updates, reading release notes, and making informed decisions about updating your resources. Broken and dull tools are even worse than no tool at all!

Folder Organization

Folder organization depends largely on your web server and middle tier language of choice. Discussing the best ways to organize folders for different servers and languages could be a cool topic for another day.

Since I use Node.js my project sandbox folder structure is pretty simple, as demonstrated below.

    • TEMPLATE (this is your Project Sandbox – copy and paste at will!)
      • startServer.js (the Project Sandbox config file)
      • PUBLIC
        • index.html
        • JS
          • main.js
          • requireLoader.js
        • CSS
          • main.css
          • responsive.css
        • FONTS
        • IMG
    • RESOURCES (libraries, frameworks, often used assets – only one copy necessary)
      • JS
        • LIBRARIES
          • jQuery (development and minified versions)
          • JQUERY PLUG-INS
            • [your favorite plug-ins here]
          • Zepto.js
          • Underscore.js
        • LOADERS
          • RequireJS
          • Modernizr (includes yepnope.js)
        • FRAMEWORKS
          • AngularJS
          • Backbone
          • Ember.js
      • CSS
        • FRAMEWORKS
          • Bootstrap
      • FONTS
        • [non-web fonts used often go here]
      • IMG
        • [logos, backgrounds, etc – include only if used frequently]

Of course, this is only a start! Your project sandbox can be tailored in any way you see fit and will change over time. The important lessons are: make one, keep it consistent, keep it current.

Good luck, and please comment with any suggestions. And as always, thank you for reading!

Table Building and Data Searching in AngularJS

Special Note: Congratulations to the AngularJS team on their 1.2.0 release! New features, better security, more stability. Read more about it on the AngularJS blog.

Before we continue I would like to quickly mention how important a good sandbox is for the rapid building and breaking of educational code. In an upcoming post I plan to cover how I configure my sandbox. For now I recommend attaching the excellent CSS framework Bootstrap to your project index.html files to take advantage of pre-constructed classes that will make your rendered markup – tables in particular – easier to read.

Preparing the Table, View Phase

Note these are View snippets – in order for these Bootstrap classes to work you must initialize the parent containers with their own Bootstrap classes. Again, more on this in a future post.

<div ng-app="myApp">
    <div ng-controller="AvengersCtrl">
        <table class="table table-striped table-bordered">
            <tr ng-repeat="actor in avengers.cast">

Did you notice?

ng-repeat="actor in avengers.cast"

The ng-repeat directive is an example of angular magic; a small directive that drives iterations through data sets without needing extensive pre-configuration. Sweet!

Preparing the Table, Controller and Service Phase

// Initialize App
var myApp = angular.module('myApp', []);

// Create the Service
myApp.factory('Avengers', function() {
    var Avengers = {};
    Avengers.cast = [
            name: "Robert Downey Jr.",
            character: "Tony Stark / Iron Man"
        // rest of the cast added here, more entries = bigger table
    return Avengers;

// Define the Controller
function AvengersCtrl($scope, Avengers) {
    $scope.avengers = Avengers;

Adding Search

Adding a Search filter, for the entire table or for a single column, only requires a small change to the View.

<input type="text" class="form-control" ng-model="search.$">

Using the dollar sign “$” refers to all available fields and is perfect for a table-wide search:


Replace the dollar sign “$” with “name” to limit searching to the name field:


Finally, enable search by adding the following:

<tr ng-repeat="actor in avengers.cast | filter:search">

In addition to outputting markup, each ng-repeat loop iteration can also be piped through a filter, as I’ve done in this example. Pattern matching is just one example; many other filters are available for even more advanced output manipulation. Refer to the AngularJS docs for more information on this awesome feature!

Shout Out

Huge credit for my continuing AngularJS education goes directly to Their awesome video library and associated sample code, most of which is FREE, is an incredible addition to the community. Thanks in particular to John Lindquist for explaining these concepts so clearly.

Thanks for reading.

A Gentle Introduction to Frameworks

A few nights ago over coffee at the local Starbucks I enjoyed one of those moments we as web developers secretly love: a full throttle conversation about ideal, multi-tiered web applications. As we broke down tiers and discussed their relationships, we considered different scenarios: what if the user is on a mobile device? What if their connection speed sucks? What if the site they are using has a million controls?

In fact, what if the website looked and needed to behave like a regular application? Would a massive collection of ad hoc jQuery event handlers, Ajax calls / RESTful services and finely crafted HTML be enough? Maybe. But a better solution exists. Enter the framework.

Frameworks and Libraries

A framework is a specialized type of library. For programming languages, a library is a collection of behaviors (think: functionality) written in terms of the language, that can be called by using a well-defined interface. Libraries are meant to be used by multiple programs or in multiple areas of a single program, largely because they encapsulate commonly used functionality set apart from the program’s actual code. This makes writing complicated code somewhat easier, as repetitive / complex chores have already been solved and are only a friendly method call away.

A library is passive. Developers must write their code using that library’s interface to get anything out of it. Thus an entire program can be written never using a library’s treasure trove of functionality, even if available the whole time. Not so with frameworks.

The Take Charge Library

Like the libraries from whence they came (poetically anyway), frameworks are a collection of functionality written in terms of the language they support. Frameworks are portable, meaning they too can be reused in multiple projects written in their given language. However, unlike a library, frameworks are bossy. Using a framework correctly means subscribing to how the framework developers view application organization and development. Let that sink in for a moment. Within a framework, your program no longer directs traffic. The framework becomes the traffic cop, and your program the exotic sports car (or three row SUV, which ever you prefer).

Frameworks share four attributes that set them apart from libraries. Where libraries are accessed as needed, frameworks work on the Hollywood Principle, aka “Don’t call us, we’ll call you.” The framework takes care of business and calls your program when it’s show time. The fancy term for this behavior is inversion of control. Second, a framework must have a default behavior, meaning once installed and properly configured, it has to do something useful right out of the box (typically a “hello world”). Next, they must afford some way for developers to extend their functionality, either by overriding default behavior or by creating new behavior within the internal guidelines. Finally, framework internals are considered off-limits. Extend all you want, look under the hood, show it off to your friends, but don’t touch anything inside. Modify the magic and you void the warranty.

Frameworks In The Wild

During my research I looked at many languages. Each of these languages had at least one framework written for them. So, while a statement like “all languages have frameworks” would probably get me in trouble, I think it is safe to say frameworks have benefits that are tough to ignore, no matter the language. Here are a few popular languages and their corresponding web frameworks:

PHP: CodeIgniter, Zend
Ruby: Padrino, Rails, Sinatra
Java: Grails, Play
Python: Django, Zope2
JavaScript: AngularJS, Ember.js, Backbone
Node.js: Express, geddy, Meteor

In fact, frameworks are so helpful they are even used in CSS. Examples include:

Foundation 3

Should I use a framework?

Frameworks are not for everybody. Some are better than others in any given situation. Frameworks can have tough learning curves, particularly for the novice developer. The unusual usage demands and seemingly arbitrary control flow may seem senseless until well understood. Framework use can also lead to code bloat by adding unnecessary functionality and inspiring work arounds written by developers unfamiliar with the framework’s complexity. Speaking of complexity, take a look under the covers and marvel at the magic. Pre-implementation study and research is sincerely recommended!

These are real concerns you should absolutely consider. However, frameworks also bring a feast to the table. As well-tested and typically open source application scaffolding, frameworks can help separate concerns in extremely reliable ways, decreasing code spaghetti. In fact code quality is often amplified when developers follow usage rules and color inside the lines. Although structured, frameworks are extensible when necessary – while still cutting development time by taking care of common tasks (just like any other library). Finally, over the long-term the framework becomes invisible, improving project delivery time and code reusability.

Thanks for reading, and happy frameworking!

Pseudo-elements as JS flags

The conventional approach to detecting screen resolution with JavaScript using RWD requires you to duplicate break points within your actual code and consequently having to maintain them in two different places. Very annoying. Using a flag embedded in each of your CSS break points is a much simpler approach because they can be programmatically accessed. Multiple flag techniques exist, but in this blog post I will discuss my personal favorite, the pseudo-element flag, invented in 2012 by Jeremy Keith and the readers of his blog adactio.


Pseudo-elements exist in an odd realm. Technically they are not part of the DOM, so they cannot be accessed via traditional selectors nor participate in regular DOM flow. Pseudo-elements, and their cousins, pseudo-classes, are CSS constructions that afford some interesting presentation options. We have all used pseudo-classes before, such as :hover, :focus, and :first-child. Pseudo-elements are used in a very similar way, but not quite as often.

The relationship between real elements and their pseudo-element counterparts:

3D diagram of element and pseudo-element relationship

Element and Pseudo-element relationship

Image Source: Nicolas Gallagher, blog entry Multiple Backgrounds and Borders with CSS 2.1 (original image revised by me to remove some copy not topical to this blog entry, and to trim it down to size).

In fact, pseudo-elements are not new – CSS1 introduced :first-line and :first-letter. CSS2 saw the arrival of :before and :after, and CSS3 has introduced the newest member of the team, ::selection. As a quick side note, CSS3 spec suggests we use double colons (::) when using pseudo-elements, to differentiate them from pseudo-classes, which use the single colon (:). However backward compatibility within browsers ensures the single colon works for both cases, and from a practical standpoint it’s probably best to still use the single colon for now.

The :before and :after pseudo-elements, having been around for many years, are in fact backward compatible all the way to IE8 (not that modern Android or iPhone users care – but it’s still good to know). The caveat however is that the HTML5 document type declaration must be used, or IE8 will poop the bed and forget everything it learned.

Building the Pseudo-Element Flag

While other techniques probably exist, the way I implement pseudo-element flags is to differentiate one at each break point. Therefore, the values contained within each set of CSS rules for each independent flag remain constant. For this reason I like to attach the flag to a relatively safe, static element, the body itself.

body:after{ }

As CSS constructs pseudo-elements enjoy CSS rules not available to conventional DOM objects. One in particular is in fact the secret in our secret sauce:


To ensure the content is not actually displayed we’ll add the final piece:


Accessing the Pseudo-Element via JS

Okay so, if a pseudo-element is not part of the actual DOM, how can we access it – or more to the point, the CSS rules defined for it? The answer:


This sweet method returns the CSS styles applied to an element and the corresponding pseudo-elements, after the browser has finished applying them. Nifty right?

function whatIsMySize() { return window.getComputedStyle(document.body,':after').getPropertyValue('content'); }

Now you have access to the value of the content property of your pseudo-element. Nice!

Last note: Firefox (maybe others, I haven’t tested them all) will return an extra set of quotes if your content value was a string. So, in the example above, Firefox would return:


Thus for conditionals I like to use:

var checkMySize = whatIsMySize();
if ( checkMySize.indexOf("mobile") != -1 ) { // off to the races }

Thanks for reading!