Compass In Hand

Guiding The Geek In You

Category Archives: Github

Welcome to 2014!

Happy New Year! It has been a few weeks since my last post. My sabbatical was refreshing and productive. I finished my first major AngularJS project, which I am excited to start writing about, and of course took some much-needed down time. I hope your end of year festivities were equally pleasant.

This year I have a diverse topic list in store for CompassInHand that I hope will be as interesting to you as it is educational to me. Technology is amazing. There is no end to what can be learned. My hope is that I can give back some of what others are teaching me.

AngularJS Project One, Released

As mentioned, I released my first application written purely in the “Angular way”: Our XBOX 360 Library (OX360L)! If you are interested in checking out the code, please visit the project git repo.

Plans for CompassInHand

Loyal readers will note: prior to my holiday sabbatical my posting interval was about once per week. Unfortunately I rarely had enough time to do the research, understand the technology, and write a quality post about it within the single week. Therefore my new posting interval will be about twice per month. The additional week will be a tremendous help and should make for tighter posts with more code examples.

While no release date exists yet, this year you can expect CompassInHand to undergo a big face lift. With the help of my good friend (and new father!) Trian Koutoufaris a new WordPress theme is slowly taking shape – including an actual site logo! Stay tuned.

Finally, I plan to begin supporting RSS feeds. This is not a big technical challenge, just an administrative oversight I never considered before. Whether this feature is useful will be up to you guys – please, comment and let me know!

What Is On The Agenda?

Lots of things!

Over the next several posts I will be discussing some of the many (many, many) lessons I learned while building OX360L. Some of these lesson topics may include:

  • The Magic of Promises
  • Implementation of JSONP based Promises
  • JSONP vs CORS, a technical compare / contrast
  • Using Directives for DOM manipulation
  • Best practices regarding $scope
  • When to use $apply / $watch / $broadcast
  • Integrating jQuery plugins into an Angular application
  • Populating the select element (ng-option v ng-repeat)
  • What is ng-cloak?

Looking past Angular / OXB360L, other post topics coming in the next several months will include:

  • Grunt “The JavaScript Task Runner” – sweet sweet process automation
  • Bower – Dependency / package installer, like npm for those of you who use node.js
  • Yeoman – Yo + Bower + Grunt equals this interesting workflow process
  • RequireJS – Great for dynamic JS library loading
  • Node.js – You can expect several posts on this topic, starting with building RESTful Web APIs
  • Bootstrap – Once a bloated CSS “framework”, now practically indispensable (for me anyway!)
  • GitHub – I use git nearly every day, but I admit I understand it poorly – let’s change that

Finally, I have another project getting ready to spin up. Look for hints and mentions as meaningful progress is made. Hopefully it can be useful for all of you who go to lunch with coworkers.

Thanks for reading!

Writing jQuery Plugins: Getting Started

Happy Post-Thanksgiving weekend everyone!

This week I begin a non-sequential series of posts describing my experiences writing plugins for the jQuery library. My idea is to cover the evolution of one – or a small set of – plugins from version 1.0 to “launch”, where launch in this case means promotioning my plugins within the massive ecosystem of the jQuery universe as loudly as possible!

The opportunity to write the first plugin for this series – Primer Carousel – came as a result of a well-designed coding challenge I recently completed. The source for this challenge is available via my public git repo here. As always your opinion is welcome; please leave your comments below or send a pull request on github.

The Wrapper

(function ( $ ) {
    $.fn.primerCarousel = function( options ) {

}( jQuery ));

The first step in writing a plugin is remembering the global namespace. Functions structured in the above format are known as Immediately-Invoked Function Expressions (IIFEs). Using the format here is essentially defensive. We want to use the $ character, but we also must be polite citizens and cooperate with other JS libraries who love the $ character. The solution: pass the function jQuery and name the parameter $, which satisfies both requirements. Perhaps the most important purpose of a IIFE, however, is that it allows private variables accessible only within the function itself.

By using .fn() object we are extending the methods made available to the jQuery object to include our plugin (which becomes just another method). Developers can therefore attach the .primerCarousel() method to any appropriate block element. Additionally, notice the use of “options”? This object contains whatever user defined settings have been made available. In version 1.0 of Primer Carousel we offer one setting, rotation speed.

Variables and Assumptions

var globlalOps = $.extend( {}, $.fn.natCarousel.defaults, options );

var filmStripWidth = 0;
var thumbNailCount = 1;

var $filmStrip = $(".filmStrip");
var $focusArrow	= $("#focusArrow");
var $filmStripCollection = $(".filmStrip").find("div");
var $smallImageCollection = $(".smallPictureRow").find("img");

var widthOfLargeImage = $filmStripCollection.width();
var widthOfSmallImages = $smallImageCollection.width();
var thumbNailArraySize = $smallImageCollection.length;

I prefer defining all of my variables up top. I know other developers prefer a “define where you use” technique – so go with what you know. There are a couple of important things to call out here. First, by using an empty object as the first passed parameter to the $.extend() method we ensure the custom defaults object is not overridden by the options object. Instead a third object is created by joining the two others.

Next, Primer Carousel relies on existing markup to function properly. This design choice speaks to a larger question: is it better to ask developers to implement a specific HTML structure for your plugin, or give the plugin a root container and rely on it to generate the HTML it needs? Obviously the later option is the most common – and from a reusability standpoint the most sensible. However, dealing with assets provided by the developer (images, for example), and operating within unique markup constraints means coding a robust evaluation system capable of detecting dimensions, calculating asymmetrical widths, and so forth. This version of Primer Carousel assumes symmetrical image width – a luxury afforded only in a test bed. Look for more robust environment evaluation logic in version 2.


// Initialize timer variable
var rotateTimer;
// Prepare film strip element containing the large image slides
$filmStripCollection.each(function() {
    var $this = $( this );
    filmStripWidth += $(this).width();
// Carousel Control - Manual
$smallImageCollection.on("click", advanceFilmStrip);
// Carousel Control - Automatic
// Pause carouseling on roll-over
this.on("mouseover", function() {
}).on("mouseleave", function() {
// Initialize, Set, and Clear Interval
function rotateTimerInit() {
    // basic position counter
    ( thumbNailCount < 3 ) ? thumbNailCount++ : thumbNailCount = 0;
function rotateTimerStart() {
    if ( typeof globlalOps.speed !== "number" ) { globlalOps.speed = 4000; }
    rotateTimer = setInterval(rotateTimerInit, globlalOps.speed);
function rotateTimerClear() { clearInterval(rotateTimer); }

You may notice the heavy reliance upon the setInterval() and clearInterval() functionality in this section? These two methods are extremely helpful when creating automated behavior. Consider wrapping them in functions to improve overall code DRY-ness, and in my opinion three timer functions work the best – initialization, start, and clear.

Also, functions defined within a IIFE formatted plugin are truly private. Returning anything back to the calling script requires return – which Primer Carousel does not need. However, if your plugin needs to be chainable then something must be returned.

Secret Sauce

function advanceFilmStrip(thumbIndex) {
    // two use cases: the thumbnail clicked or function fired automatically
    if ( typeof thumbIndex === "object" ) {
       var $this = $( this );
       var thumbPosition = $smallImageCollection.index(this);
       var smallImageLeftMargin = $this.css("marginLeft");
    } else {
       var thumbPosition = thumbIndex;
       var smallImageLeftMargin = $smallImageCollection.eq(thumbIndex).css("marginLeft");
    // Convert px measurement to an integer
    smallImageLeftMargin = (smallImageLeftMargin.replace("px","")) * 1;
    // Calculate current position
    var filmStripPosition = widthOfLargeImage * thumbPosition * -1;
    var focusArrowPosition = (widthOfSmallImages + smallImageLeftMargin) * thumbPosition;
    // move the images

The secret sauce is all right here. You probably noticed the typeof check made on the incoming parameter? This is done because of the dual use cases in which advanceFilmStrip is called. In my opinion this is a mistake, I should only ever need to accommodate for a single parameter type (in this case, object or integer).

Being Kind

$.fn.natCarousel.defaults = {

Being kind in this case means saving developers the effort of hunting through our source code to find where we configure our default plugin options. This object should contain the entire range of all available options – version 2 of Primer Carousel will have several more, including spin direction, animation, and on-screen controls.

In my opinion, just because your plugin CAN do something does not mean it must – nor does it mean those functions must be documented for the end user. Think carefully about what features users will want and refine accordingly. Also, use conventions! Primer Carousel’s speed setting accepts an integer, and passes (with error checking, naturally) that value directly to the setInterval method. Abstract settings like “fast” or “ultra slow” simply add an additional layer of complexity. The goal is to make developers want to use our plugins because they work exactly as expected, reliably, and with a minimal education required. Keep it simple!

Thanks for reading!