An Emerging Paradigm
Old School Jump Menus
Here is a simple script that I used frequently in web applications to make jump menus. A jump menu, in this context, is a
<select> form element that, when an option is chosen, redirects you to another page/website.
<select onchange="if( this.options[this.selectedIndex].value != '' ) location.href=this.options[this.selectedIndex].value;"> <option value=""></option> <option value="http://google.com/">Google</option> <option value="http://yahoo.com/">Yahoo!</option> <option value="http://ask.com/">Ask.com</option> </select>
onclick for a customized button)? It would be much easier to manage if you could tuck all that code away into the
<head> section of your XHTML or, better yet, in a separate file altogether.
A New Perspective
Take the jump menu script, for example. When coded unobtrusively, the XHTML looks like this:
<select id="jm1" class="jumpmenu"> <option value=""></option> <option value="http://google.com/">Google</option> <option value="http://yahoo.com/">Yahoo!</option> <option value="http://ask.com/">Ask.com</option> </select>
Notice that the
jumpmenu class was assigned to the
<select> element. I've also added a unique ID so the script can determine which URL should be used when an event is triggered.
Now we have to write the code to turn all
<select> elements with the
jumpmenu class assigned to them into jump menus.
When the page loads, the script populates a list of all
<select> elements in the document using the
initJumpMenus() function. Then it adds the appropriate
onchange event to those elements that are assigned the
jumpmenu class. Simple.
The Benefits of UJS
That's a lot more code than the original example had. At first glance, it doesn't seem like it's worth all of the extra steps. With UJS, the initial investment usually seems a bit more than the return. But what if we wanted to add another jump menu? Simple. Add another
<select> element with the
Similar to the way you can manage the style of a class using CSS, you can manage the behavior of a class using UJS. In my opinion, that's much better than the traditional method of going page to page and copying and pasting inline code snippets.