Javascript Unit Tests with TravisCI and QUnit

I wanted to make an update to my Bingo Card Generator. Previously I’d added automated tests for JSHint via TravisCI to test for code formatting, but now I wanted to actually test code functionality. I decided to add a simple unit test using QUnit.

I made a lot of mistakes trying to get this to work (probably because I didn’t read the documentation!), so I’ve included all my steps and missteps below in case they are useful to someone else:
Continue reading Javascript Unit Tests with TravisCI and QUnit

Using getResponseHeader with jQuery’s ajax method

The Canvas API uses pagination for requests that return multiple items. The URL of the next result set is specified in an HTTP response header. I know how to get the response body, but how do I get the response headers from a jQuery AJAX call?

The jQuery ajax documentation indicates that the “[jqXHR] object returned by $.ajax() as of jQuery 1.5 is a superset of the browser’s native XMLHttpRequest object.” And the XMLHttpRequest object includes a getResponseHeader method.

At first I tried calling getResponseHeader as a method of the data object:

$.ajax({
    url:'/api/v1/courses'
}).done(function (data) {
    console.log(data.getResponseHeader('Link'));
});

But data contained just the response body, and data.getResponseHeader was null.

A closer look at the jQuery documentation indicated that additional objects are passed to the done function, including the jqXHR object. Accessing that object’s getResponseHeader method worked:

$.ajax({
    url:'/api/v1/courses'
}).done(function (data, textStatus, xhr) { 
    console.log(xhr.getResponseHeader('Link')); 
});

Balancing Tags in HTML and XHTML Excerpts

It is fairly common to want to take an HTML source of variable length and display an excerpt. Although some formats, such as Atom and RSS, anticipate this and create a separate summary element, we don’t always have the luxury of using such a data source.

Creating an excerpt introduces a problem, though: if we create an excerpt based on a number of words or characters, we may end up with unbalanced HTML or even broken tags.

One solution is to discard all tags and display plain text, but this is often unsatisfactory.

Here is my method of balancing tags. It assumes that the input is an excerpt of a valid XHTML snippet. The reason for this requirement has to do with self-closing tags, which I hope will be apparent from the description:
Continue reading Balancing Tags in HTML and XHTML Excerpts

Javascript Array Sort & Random Ordering

Recently a colleague and I were looking at some Javascript code that randomizes a list of elements. The code did this by creating an array of list-item elements, and then passing a comparison function that returns a random result to the array.sort() method. Unfortunately, the random order was anything but random: after reloading the page 50 times, the distribution was skewed heavily towards the original array ordering.

In case you don’t feel like reading my entire exploration of this topic, I’ll give you the short version:
Don’t use array.sort() to randomize arrays! There are methods of randomizing arrays that produce better (i.e. more random) results, and that are (probably) faster.
Continue reading Javascript Array Sort & Random Ordering

Douglas Crockford: “Programming Style and Your Brain”

On 13 January, 2012, I saw Javascript expert Douglas Crockford deliver a talk titled “Programming Style and Your Brain” on the campus of the University of Pennsylvania. The brain portion of the talk (which Mr Crockford said borrowed heavily from Daniel Kahneman’s book Thinking, Fast and Slow) was really just to emphasize that human beings have 2 distinct ways of thinking: Head (slow) and Gut (fast). Computer programming requires some of both, but the same Gut-thinking that can provide useful insights can sometimes also lead us astray.

For example, programmers have been arguing since the 1970s about the placement of curly braces. Some people prefer:

if ( true ) {
doSomething();
}

Others prefer:

if ( true )
{
doSomething();
}

Crockford says that if the compiler treats these 2 forms as equivalent, then there is really no difference (so long as you are consistent). These are Gut decisions. However, people will use their Head to try to rationalize their Gut decisions and come up with some ridiculous rationalizations.

OK, fine. What does that mean in practical terms, i.e. writing code?
Continue reading Douglas Crockford: “Programming Style and Your Brain”

SharePoint user control to display a random image

The master page of a SharePoint site I work on loaded 7 photographic images, all over 50 kB each, to display at random as a banner adjacent to the site logo. The way it loaded the images was very inefficient: a default image was loaded in the HTML, and Javascript on the page created 7 image objects and returned one at random to overwrite the default. I decided to find a C# way to solve the problem.
Continue reading SharePoint user control to display a random image

Opening links in a new window without the target attribute

Web developers often use the attribute target="_blank" to force a link to open in a new window. However, if you use an HTML validation service to check your web pages, you know that the target attribute is not valid in strict versions of HTML and XHTML.

There is a simple way to have a link open in a new window using Javascript. You may have seen code like this:
<a href="#" onclick="window.open('http://osric.net')">osric.net web hosting</a>

That method has some serious drawbacks, though:

  • The user now sees # in the browser’s status bar instead of the actual destination URL
  • The link fails if the Javascript fails (or if the browser has Javascript disabled
  • Search engines may not follow the link

I’ve written a summary of the issue and the methods I’ve found so far that best address it. I moved it to a page outside this blog because of the Javascript examples, which were easier to include on a separate page:

How to best use Javascript to open links in a new window

More People Alive Today Than Have Ever Died

A few years ago, I ran across this quote:
“There are more people alive today than have ever died.”

As we contemplate overpopulation, a quote like that is quite thought-provoking and shocking. Could it be that the living today outnumber all of our ancestors? It’s astounding. However, I didn’t believe it. I still don’t believe it, and for good reason.
Continue reading More People Alive Today Than Have Ever Died

JSONP and Sencha Touch

I was recently trying to get a Sencha Touch demo up-and-running, but my callback functions after requests for JSON data never ran, and Firefox would throw errors along the lines of “invalid label.” I didn’t understand why–until I read more about JSONP.

JSONP prefixes your JSON response with a function name, which runs when the response is retrieved. It’s a way of handling the data without a listener.

This means that your JSONP provider needs to detect a JSONP parameter, and then wrap or “pad” the response within the specified parameter value.

For Sencha Touch, the JSON returned should be wrapped in Ext.util.JSONP.callback();. If your JSON looks like this:

{"results":[{"name":"Chris"},{"name","Harry"}]}

then your JSONP should look like this:

Ext.util.JSONP.callback({"results":[{"name":"Chris"},{"name","Harry"}]});

Not that you should hard-code that function name anywhere in your JSON output–web-based APIs and services should pick up the function from your request and wrap the JSON for you. For example, the twitter search API accepts a callback querystring parameter.

http://search.twitter.com/search.json?q=fakecriterions&callback=myCallbackFunction

would wrap the JSON response inside

myCallbackFunction();

I ignored the extra letter in the acronym at my own peril–I figured it was just a trivial variation on JSON (which it is) that wouldn’t make any difference in how it was handled (but it does).