Monday, May 10, 2010

Creating jQuery plug-ins for an unordered list

I've been writing a lot more JavaScript recently, sometime's following other peoples code and sometime's writing my own from scratch. A lot of this JavaScript has been done using jQuery. As most of our development team was new to JavaScript the code quickly became unstructured and messy. There had to be a better way.

I was really pleased to discover that it didn't have to be this way and jQuery had created a really easy to use plug-in architecture. As you'll see from this quick guide it's very easy to create a neat and elegant JavaScript solution using a jQuery plug-in. What I really like about the jQuery plug-in solution is that it makes it easy to provide "Progressive Enhancement" to your site. So that if JavaScript has been disabled, the mark-up will remain unchanged. It' like you are rewarding people with JavaScript and providing a richer browsing experience.

The following example is similar to a real world example I was recently asked to create. The client wanted an un-ordered list to only show the first 5 elements and then provide the user with a link to see the other element. They also wanted the list to be sorted. For this I decided to break the problem down into it's 2 parts.

Part 1 would be to create a "listsort" plug-in, Part 2 would be the "hideextra" plug-in to
show/hide the extra elements.

Here's what the final List ended up looking like:

...and these are the steps to create the above: