http://www.developer.com/

Back to article

Make Your Site Script.aculo.us


January 3, 2007

In my previous article, I introduced a lot of different AJAX frameworks. In this article, I will look in more detail at the Script.aculo.us framework and discuss why you may want to use it in your web applications. Script.aculo.us is purely a client-side framework that gives developers a new way to code in JavaScript by providing new shortcut functions, new powerful objects including Form, Effect, Control and Ajax, and some custom widgets. Script.aculo.us is really not an independent product, but an add-on to the Prototype.js JavaScript library developed and maintained by Sam Stephenson. Prototype by itself is a very well thought out and implemented library of JavaScript methods that helps a great deal with creating rich, highly interactive, and dynamic web pages. Script.aculo.us builds on the existing Prototype implementation. It enhances Prototype by adding effects and controls, morphing, and custom UI widgets such as a Slider.

Among different AJAX and JavaScript frameworks, Script.aculo.us (and Prototype) has been on the forefront of the Web 2.0 movement. Even though it is not a "one-stop-shop" AJAX commercial framework such as Backbase or IceFaces, it still delivers a lot of functionality, time-saving features, and amazing effects with a MIT license. This means that you can use it free of charge for anything you like (which includes commercial applications), but cannot remove the copyright remarks. As of this writing, the Script.aculo.us stable version is 1.6.5, but a beta 1.7 with new morphing effects has just been released. If you are a web developer, dealing with a lot of JavaScript code, and wondering how to add effect to your site, or want to join the Web 2.0 and AJAX movement, you need to give the Script.aculo.us framework a good look.

The framework is standards-compliant, and behind the scenes takes care of the browser compatibility issues for major supported browsers, which are Internet Explorer, Firefox, and Apple's Safari. It is server technology agnostic and can easily integrate with these server technologies: Ruby On Rails, Perl, Nitro, PHP, Java, Plone, Pylons, DotNet, Symfony, Seaside, and OpenACS.

Installing Script.aculo.us Files

Because Script.aculo.us only consists of several JavaScript files, it has a very small footprint. The files need to be placed somewhere on the web server in the visible directory and then referenced in your code. I have installed the 1.7 version, under js/ext/s17 directory; therefore, my reference looks like this:

<script language="JavaScript"
        type="text/javascript"
        src="js/ext/s17/prototype.js"></script>
<script language="JavaScript"
        type="text/javascript"
        src="js/ext/s17/scriptaculous.js"></script>

By default, Script.aculo.us loads all of the other JavaScript files necessary for effects, drag-and-drop, sliders, and all of the other Script.aculo.us features. If you don't need all of the features, you can limit the additional scripts that get loaded by specifying them in a comma-separated list. Ex:

<script src="scriptaculous.js?load=effects,dragdrop"
        type=...></script>

The scripts that can be specified (to be loaded) are: builder, effects, dragdrop, controls and slider.

This is really all you need to start harnessing the power hidden in this library. So, start coding!

Script.aculo.us Functions

The Prototype library included with the framework is a collection of JavaScript functions and objects that greatly simplify working with the DOM manipulation and JavaScript in general. New functions for working with AJAX, DHTML effects, a module for drag-and-drop functionality, a module for various custom controls, and a custom widget such as a Slider have been added in Script.aculo.us on top of the Prototype library. In other words, the functions that simplify working with the Document Object Model (DOM) are part of the Prototype library and all of the custom widgets and controls are part of the Script.aculo.us framework.

The big problem with modern web development is existence of the choice of many web browsers. For the casual web user, it is great because competition among browser vendors ultimately creates better a product. However, for web developers it is a nightmare. Different vendors implement JavaScript in many ways. On top of that, CSS styles are interpreted in different ways and even HTML tags may exist in one browser but be a novelty in another. The problem can also affect the various release versions from the same vendor. Microsoft, for example, is known to introduce new non-standard methods with each browser release.

Therefore, very often developers run into compatibility issues with their code with various browser versions and platforms. Instead of concentrating on writing solid logic, they start concentrating on detecting browser versions and writing different versions of code to tailor a specific platform. Additionally, developers who want to control events or add effects to their pages often end up creating their own (multi-browser) implementation. Many limitations in JavaScript itself force developers to create lofts of code to do simple things; for instance, traversing all elements with the same CSS style (class name).

The Script.aculo.us framework (or rather Prototype) introduces a lot of many shorthand notations and shortcuts into the JavaScript way of writing code and under the hood takes care of the cross-browser compatibility. In general, JavaScript in Web 2.0 sites is used to accessing and manipulating Document Object Model of elements loaded on the page. For instance, if I have a <div> element, I may want to populate it with the response of an asynchronous AJAX call to the server. For that, I need to access the object and set its innerHTML to the response text. To locate the div element, I need to start with the root of the DOM, or document object, and then get the element I am interested by its DOM id. For example:

// somewhere on the page
<div id='vlad'><div>

// In my JS callback function
myElement = document.getElementById("vlad");
myElement.innerHTML = xmlHttp.responseText;

One of the many useful shorthand notations that Script.aculo.us has is the dollar $() function. This is a Prototype shortcut to reference to DOM elements by their id. The same code now looks like this:

myElement = $("vlad");
myElement.innerHTML = xmlHttp.responseText;

You may be saying now, okay less typing, not a big deal. But, this little shortcut is also very powerful—it can take multiple ids and return an array or elements.

nodes = $("vlad", "mariya");
for(i = 0; i < nodes.length; i++) {
   alert(nodes[i].innerHTML);
}

Other Shorthand Dollar Functions

Other shorthand dollar functions with existing and new functionalities are:

$F(), $A(), $H(), and $R()

$F() returns a reference to a field input control from the form—very easy and very useful. For example:

<form>
   <input type="text" id="name" value="Vlad">
   ..
</form>

<script>
   alert( $F('name') );
</script>

$A() converts any argument passed into it as an array—yet another greatly useful shortcut.

<script>
function someFunc(){
var someNodeList = $('someElement').getElementsByTagName('option');
var nodes = $A(someNodeList);
   for(i = 0; i < nodes.length; i++) {
   alert(node.innerHTML);
   }
}
</script>

$H() converts objects into enumerable Hash objects that resemble associative arrays.

The $R() function is a shorthand to writing new ObjectRange(lowerBound, upperBound, excludeBounds), but more on the objects later.

Here is a great chart by Jonathan Snook, showing functions and object available in the Prototype library.



Click here for a larger image.

It's a Bird. It's a Plane. No, it's Script.aculo.us

Script.aculo.us (and the underlining Prototype library) not only introduces useful shortcuts but it also gives developers brand new JavaScript objects and new extensions on the existing objects. This creates an entirely new coding style, in many cases simpler and more robust.

For instance, to iterate over an array in JavaScript a "for" loop is usually used, such as this:

for(i=0;i< someArray.length;i++){
   alert(someArray [i]);
}

However, the Script.aculo.us iteration is more powerful and requires less coding:

someArray.each( function(current){ alert(current); });

Some new objects introduced with Prototype are Hash, Form, Try, Enumerable, and of course Ajax. The effects and controls introduced with Script.aculo.us are part of the objects, called Effect and Control, respectively. The core or combination effects can be added simply by calling Effect.effectName and passing the element's DOM id. If you have loaded the effects module, you can start adding various effects such as glowing, puffing, scaling, blinds, shrinking, and morphing to any element on the page.

For example, here are some effects on the onClick event:

<div onclick="new Effect.SwitchOff(this)">
   Click here to switch off.
</div>

<div onclick="new Effect.BlindUp(this, {duration: 5})">
   Click here to see blind up effect.
</div>

The new morphing feature can be called on the element without using the Effect object. For example, passing a CSS style name or definition will create a morphing effect in JavaScript.

style='font-family:Verdana;color:#333399'><style>
   .warning {
      font-size: 15px;
      color: #f00;
      border: 4px soild #f00;
   }
</style>

<script>
   $('mydiv').morph({fontSize:'20px',color:'#abcdef'});
   $('myWdiv').morph('warning');
</script>

<div id="myDiv">
   Hello world
</div>

<div id="myWDiv">
   Warning!
</div>

The five core effects—Effect.Opacity, Effect.Scale, Effect.MoveBy, Effect.Highlight, and Effect.Parallel—are the foundation of the Script.aculo.us Visual Effects JavaScript library. All other combination effects are based on core effects. Developers also can write their own effects.

For more information on the available effects, please see the reference section and a great cheat sheet by Amy Hoy.

Script.aculo.us AJAX

The power of the Script.aculo.us framework lays with the amalgamation of the all of the effects, coding shortcuts, new powerful objects, extension of existing objects, and most importantly AJAX. The Script.aculo.us framework wound not be a true Web 2.0 framework without AJAX support. The Ajax JavaScript Object is actually part of the Prototype library, but many controls and widgets in the Script.aculo.us framework are AJAX-enabled. For instance, the Auto-completion module is AJAX enabled.

The Ajax Object hides the multi platform instantiation logic for the XMLHttpRequest object and also provides a lot of powerful wrapper methods (and other extended objects) to simplify working with the asynchronous server communication.

For instance, here are some of the AJAX objects:

  • Ajax.getTransport(): Returns a new XMLHttpRequest
  • Ajax.Request: Encapsulates AJAX operations
  • Ajax.Updater: Returns HTML to inject directly in a specific element of the page or to return script blocks to be evaluated
  • Ajax.PeriodicalUpdater: Repeatedly instantiates an Ajax.Updater object to refresh an element on the page multiple times

Please see the Script.aculo.us online documentation for more Objects and APIs relating to AJAX.

Conclusion

In this article, I have covered some of the basics of the Script.aculo.us framework. This framework may not provide all the bells and whistles of the other commercial frameworks, but it is server technology agnostic and provides essential tools for any web developer. Some of the features that come with the Script.aculo.us JavaScript libraries—such as animation framework, drag and drop, AJAX controls, DOM utilities, and unit testing—are truly time savers. If used right, the framwrok can add fantastic usability features to the site with the resulting cross-browser compatible code.

Given the fact that there is practically no configuration, a small learning curve, and lots of benefits, you practically owe it to yourself to at least take a look at this client-side framework. And, if you are already looking for a quick way to add some interesting visual effects and AJAX-enable you existing web pages, Script.aculo.us can be a great solution.

Source Code (Includes Script.aculo.us 1.7)

Download the Source Code here.

References

About the Author

Vlad Kofman works on enterprise-scale projects for the major Wall Street firms. He has also worked on the defense contracts for the U.S. government. His main interests are object-oriented programming methodologies, UI, and design patterns.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date