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:

My Web App <%= javascript_include_tag "prototype", "effects" %> <%= @content_for_layout %>

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

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.

Table 15-1.

JavaScript initialization

Rails initialization

new Effect.Highlight

visual_effect(:highlight)

new Effect.Appear

visual_effect(:appear)

new Effect.Fade

visual_effect(:fade)

new Effect.Puff

visual_effect(:puff)

new Effect.BlindDown

visual_effect(:blind_down)

new Effect.BlindUp

visual_effect(:blind_up)

new Effect.SwitchOff

visual_effect(:switch_off)

new Effect.SlideDown

visual_effect(:slide_down)

new Effect.SlideUp

visual_effect(:slide_up)

new Effect.DropOut

visual_effect(:drop_out)

new Effect.Shake

visual_effect(:shake)

new Effect.Pulsate

visual_effect(:pulsate)

new Effect.Squish

visual_effect(:squish)

new Effect.Fold

visual_effect(:fold)

new Effect.Grow

visual_effect(:grow)

new Effect.Shrink

visual_effect(:shrink)

new Effect.ScrollTo

visual_effect(:scroll_to)

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"

Категории