Progressive enhancement with jQuery

I’ve been having a lot of fun with jQuery recently. One of the things particularly easy to do with it is write nice and unobtrusive javascript (a good start when looking at progressive enhancement). This is largely down to the fact that it’s very easy to find particular elements within the DOM - with any level of specificity - and attach behaviour to them.

On the site I’ve been building at work, one particular example was to get jQuery to write in the “Print page” link, since that needs javascript.

// add print page link - since it can only work for JS, only add it for JS users
$('<li></li>') // create list item
    .addClass('print') //add relevant class to it
    .append('<a href="javascript:window.print();">Print this page</a>') //put in the link
    .insertBefore('li a.foo'); //add before the li item with link of class 'foo'

The above example is slightly more verbose than it need be, but it illustrates some of the different built-in functionalities of jQuery quite well.

Another example was to attach popup window behaviour to a couple of the links, while avoiding two particular ways this is sometimes done.

<a href="javascript:function();">Foo</a>
<a href="foo.html" onclick="function();" onkeypress="function();">Bar</a>

The first is inaccessible, because there’s no non-javascript alternative. The second is somewhat obtrusive - the javascript code sits around regardless of whether it can actually be used or not. Additionally, it doesn’t take into account which key has been pressed, which will be a problem for users who are tabbing between links.

Hooking the javascript functionality onto the links is very easy. Assuming a link with class ‘popup’, you’d do the following:

//attach js funtionality to a link
$('a.popup').bind('click keypress', function(event) {
    var code=event.charCode || event.keyCode;
    if(!code || (code && code == 13)) {// if no key code (mouse) or if enter is pressed
        [...]; // do whatever we need to do
        event.preventDefault(); //prevent browser from following the actual href
    }
});

To make this easier to re-use, I ended up writing a little jQuery plugin (see it in action). The function essentially allows binding of mouse click and Enter keypress to a specified element. On either of those events, a given function is called, and the default action is blocked (which, for a link, is to follow the link).

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment