With jQuery, Awesomeness Abounds

While my job has primarily used PrototypeJS in the year-and-a-half I've been here, we've recently started shifting toward jQuery.

My favorite reasons for the switch:

  1. Vibrant plugin-ecosystem: — There are easy-to-use and well-documented plugins for almost anything you can think of. Plus you have great expansions like jQuery UI and jQTouch
  2. Easy to write, easy to read — While the basic functionality of Prototype and jQuery is pretty similar, I find jQuery code to be slightly more compact to write and easier to read.

The jQuery API is full of all kinds of handy functions. I encourage browsing it on a regular basis. You never know what you may find that will help solve the problem at hand.

For example, last week I discovered the jQuery.data() function which lets you store arbitrary data associated with an element. The data is stored using key/value pairs (and retrieved by key).

I was working on a very simple web-based survey and needed to show/hide some questions based on the responses to previous questions. I was originally going to create a global array/hash and do lookups into that, but the data() function seemed like a cleaner way to handle storing the show/hide info.

Here's a simple example of how it works.

Let's say our survey consists of the following HTML:

~~~~ {.html name="code"}

gt; Choice 1
gt; Choice 2
gt; Choice 3
gt; gt; gt;
gt; wzxhzdk:0

And here's the code for the showHide() function:

~~~~ {.javascript name="code"} function showHide(elem) { if(elem.checked) { if($(elem).data('hide')) { $($(elem).data('hide')).each( function(i) { $(this).hide(); this.checked = false; }); } if($(elem).data('show')) { $($(elem).data('show')).each( function(i) { $(this).show(); }); } } } wzxhzdk:1