Adding DHTML Effects with script.aculo.us
Problem
You want to add fancy effects such as fades to your application, without writing any JavaScript.
Solution
Every Rails application comes bundled with some JavaScript libraries that allow you to create Ajax and DHTML effects. You don even have to write JavaScript to enable DHTML in your Rails web site.
First edit your main layout template (see Recipe 15.3) to call javascript_include_tag within your tag:
Now within your views you can call the visual_effect method to accomplish the DHTML tricks found in the script.aculo.us library.
Heres an example of the "highlight" effect:
Here is some important text, it will be highlighted when the page loads.
Heres an example of the "fade" effect:
Here is some old text, it will fade away when the page loads.
Discussion
The sample code snippets above are triggered when the page loads, because they e enclosed in tags. In a real application, youll probably display text effects in response to user actions: deleted items might fade away, or the selection of one item might highlight related items. Heres an image that gets squished when you click the link below it:
The JavaScript code generated by the visual_effect method looks a lot like the arguments you passed into the method. For instance, this piece of a Rails view:
Generates this JavaScript:
This similarity means that documentation for the script.aculo.us library is almost directly applicable to visual_effect. It also means that if you feel more comfortable writing straight JavaScript, your code will still be fairly understandable to someone who knows visual_effect.
The following table lists many of the effects available in Rails 1.0.
See Also
- The script.aculo.us demo (http://wiki.script.aculo.us/scriptaculous/show/CombinationEffectsDemo)
- Recipe 15.3, "Creating a Layout for Your Header and Footer," has more on layout templates
- Recipe 15.17, "Creating an Ajax Form"
Категории