Archive for the ‘Usability’ Category

Unobtrusive Javascript. Gracefully degrading event driven elements.

Tuesday, April 15th, 2008

When working on the right hand navigation pane for this blog I really wanted to keep things simple and clutter-free. Too many blogs try to throw a million links at you on their sidebars. I don’t have an extensive topic list yet, but an example would probably be Ajaxian … plus the millions of other blogs out there that use WordPress. I’m not aware of any plugin or setting that fixes this… suffice to say though, if one does exist, Its not used widely enough.

The choice I made was a simple drop down menu, but theres nothing particularly fascinating about that (I just used a couple of Appear Effects… I’ll touch on this a bit more later).

There was a problem that i quickly faced with the implementation, and that was the lack of a link to attach an event to. As an example, the “Archives” header on the right.

  1. Theres no Archives ‘root’ that I’m aware of, so I couldn’t just whack a link in there.
  2. I wasn’t going to create a link with no target URL. Not nice to people with JavaScript disabled.
  3. CSS could be used by assigning cursor: ‘pointer’ to the header. But I don’t consider that best practice for usability when JavaScript is disabled. Users without JavaScript could think it was click-able.

We’re going for proper graceful degradation here. For this implementation, we’ll be using my favourite frameworks, Prototype and Script.aculo.us.

Getting it fixed.

Theres two ways I could think of that you can go about fixing this, and its really just a matter of preference (please do make a suggestion If I’ve missed something). One would be to wrap a link around the Header using javascript, then adding events to the link. Assuming categories is the header2 element you want to manipulate. You could employ a method similar to this:

$('categories').update('<a href="" id="categories_link">' + $('categories').innerHTML + '</a>');

Then add an event to the a link, as such:

Event.observe('categories_link', 'click', function() {
// Do stuff
}

I didn’t use this method, and haven’t tested it myself, but it would probably work just as well.

The method I implemented was to basically add the cursor style to the h2 element, so the element is shown to be a clickable object.

$('categories').setStyle({ cursor: 'pointer' });

Then add the event:

Event.observe('categories', 'click', function() {
// Do stuff
}

And thats it! Done. Damn simple stuff.

We solve the issue of having a pointless link for those without JavaScript and we also simulate link behavior for those with JavaScript. Simple one line of code that makes your site just that little bit more usable.

Note for this example I’ve used completely different code to illustrate my point. You can see how I’ve implemented it in my run.js file.