Topics:
apps
css
games
javascript
mobile
node
php
speaking
tehcl
textmate
tools
video
webgl

Topic: javascript

Fix jQuery UI Tabs to Update Browser Location

published:
2009.06.08
topics:
javascript

When I spoke at MinneWebCon 2009 about Standardizing Web User Interfaces I covered one of my major pet peeves on the web: when content that can and should have a direct link, does not.

(The most common example would be the all-Flash portfolios and galleries of designers. You get three pages into their sites looking at a particular piece of their work, and then you look up in your browser location bar and you are still at http://www.stupid-designer.com/ ... I can't share their design work with somebody even if I wanted to, because there is no link! Terrible SEO and self-promotion.</rant>)

In terms of web user interface widgets, the very common tab view is often done incorrectly. For instance, both YUI's tab view and jQuery UI's tab view fail to change the browser's location when you switch tabs.

You can already directly link to a tab if you know the URL or right-click the tab to find the URL. However, if I use my browser's default bookmarking behavior, or if I use the location bar to copy and paste a link to somebody, or any number of other scenarios — because neither the YUI nor jQuery's tab views update the browsers location when you switch tabs, you are likely to send somebody a link to the first tab you landed on rather than the tab you are viewing.

The strangest part of all this is that enabling the direct linking on the back end is actually the hard part. Getting the location to update as you switch tabs is laughably easy. Here is the code for the default jQuery tab view behavior:

$('#tabs').tabs();
To fix the jQuery tab view so that it updates the browsers location as you switch tabs, the code looks like this:

$('#tabs').tabs();
$('#tabs ul li a').click(function () {location.hash = $(this).attr('href');});

Couldn't be simpler. I've set it up so you can see it in action. In this fixed jQuery tabs example as you click the tabs you will see your browser's location update.

I have submitted a ticket.


jQuery Syntax for Easy Portability?

published:
2009.06.03
topics:
javascript

I have to say, I find the syntax of the jQuery JavaScript library to be very logical, efficient, and readable. I realized today that jQuery code also has the very interesting property of being relatively easy to port to any other JavaScript library. And jQuery, or a jQuery-like syntax, seems to be a reasonable starting point for creating JavaScript-library-agnostic code — that is, JavaScript code that depends on a JavaScript library to function, but can be easily made to work with any library.

As an example, lets consider the following jQuery call:

$('#foo,#bar').addClass('test').css('color', 'blue');
Now lets look at code that does the same thing written for YUI and Dojo:

// YUI
YAHOO.util.Dom.addClass(['foo', 'bar'], 'test');
YAHOO.util.Dom.setStyle(['foo', 'bar'], 'color', 'blue');

// Dojo
dojo.query('#foo,#bar').addClass('test').style('color', 'blue');

Lets say we wanted to keep the jQuery syntax shown in the very first example above, but instead of including jquery.js and all of the jQuery code, we wanted to use the YUI JavaScript library. How could we make the jQuery style call use YUI? Here's some code that maps those calls to the YUI library:

function UseYUI(selector) {
    this.nodes = YAHOO.util.Selector.query(selector);

    this.addClass = function (className) {
        YAHOO.util.Dom.addClass(this.nodes, className);

        return this;
    }

    this.css = function (property, value) {
        if (typeof value == 'undefined') {
            return YAHOO.util.Dom.getStyle(this.nodes, property);

        } else {
            YAHOO.util.Dom.setStyle(this.nodes, property, value);

            return this;
        }
    }
}

function $(selector) {
    return new UseYUI(selector);
}

After adding the above code to your page you could keep the jQuery syntax — i.e. $('#foo,#bar').addClass(… — but include the YUI library code and files instead of the code and files for jQuery.

And actually, if we had many methods like addClass where they are the same in jQuery and YUI except for the first argument, we could create a helper function to generate the mapped functions for us:

function UseYUI(selector) {
    this.nodes = YAHOO.util.Selector.query(selector);
    
    this.mapMethodToYUIDom = function(method) {
        this[method] = function () {
            var args = new Array();
            args.push(this.nodes);
            for (var i = 0; i < arguments.length; i++) {
                args.push(arguments[i]);
            }
        
            YAHOO.util.Dom[method].apply(null, args)
        
            return this;
        }
    }

    this.mapMethodToYUIDom('addClass');
    this.mapMethodToYUIDom('removeClass');
}

Mapping the jQuery style calls to Dojo in this case is even easier than YUI. Much easier:

function $(selector) {
    var nodes = dojo.query(selector);

    nodes.css = nodes.style;

    return nodes;
}

It would be a fair amount of work, and a decent bulk of code, to completely map all jQuery style calls to either YUI or Dojo, or any other JavaScript library for that matter. Obviously, when porting from one JavaScript library to another, going through line by line and replacing each call would result in slightly faster and more file-size efficient code. But that's no walk in the park either.

With the method I've described in this post, you could actually put in the one-time effort towards creating the code to dynamically map from jQuery syntax to any other framework thereby making any and all projects you build and distribute library-agnostic. What do you think? It seems like such mappings would come in useful.


Patch jQuery fadeTo() to Bring Back the Dead

published:
2009.05.14
topics:
javascript

Well, maybe not bringing back the dead exactly, but I did patch the jQuery function fadeTo() to bring back elements after hide() or fadeOut() were called on them.

Just paste this in your JavaScript after you load jQuery:

/**
 * Fix jQuery fadeTo() so it can bring back something after hide() or fadeOut()
 */
(function ($) {
    var proxied = $.fn.fadeTo;
    $.fn.fadeTo = function() {
        if ($(this).is(':hidden')) {
            $(this).css('opacity', 0).show();
        }
        
        return proxied.apply(this, arguments);
    }
})(jQuery);

I'd like to just see them fix this in the library itself, so I submitted a ticket.


Pattern for JavaScript Options with Defaults

published:
2009.05.14
topics:
javascript

Maybe this is obvious, but here's a really handy pattern for passing an object of options into your JavaScript functions when you also want there to be a set of default options for that function. I'm using jQuery's $.extend function to handle the objects, but most JavaScript libraries provide this functionality.

function myFunction(arg1, options) {
	var defaultOptions = {
		foo: 'foo-default',
		bar: 'bar-default'
	}
	
	if (typeof options == 'object') {
		options = $.extend(defaultOptions, options);
	} else {
		options = defaultOptions;
	}
	
	// rest of your code here...
	
	// for demonstration purposes
	alert(options.foo + ' and ' + options.bar);
}

Try running some demonstration code by clicking these buttons:

I hope somebody found that interesting/helpful.


Best 1st Day Back Ever: Video Game Award!

published:
2009.05.08
topics:
games
javascript

If you follow me on Twitter then you've probably learned by now that I've been out of the office at my day job because I had an emergency appendectomy. Today was my first day back, and I have to say I had a pretty good morning because I found out that a video game I made with my web team last spring — Handy Andy 2: The Ampersand Trail — won an award! (So now I can say I am an award winning video game developer. Heh.)

Me holding the award.
The Handy Andy 2 title screen graphic.

Hey, it is a Friday afternoon, you know that you totally want to spend it "researching" this game rather than working. And when you've finished playing Handy Andy 2, you definitely will want to check out the first game, Handy Andy's Key Quest, and play some Handy Andy Bowling.

Congratulations to the Handy Andy 2 team! Kamran Ayub did the graphics and Jesse Mullan did the sound, and both contributed to the overall insanity and level design. The games are written in JavaScript with a Flash bridge for the audio if you were wondering.