Wednesday, September 10, 2008

Using RJS without calling the server

If you want an easy way to use visual effects on your page or to manipulate the DOM in an AJAX style way but without making a call to the server, then take a look at this helper method...

Sometimes there are times when you want to use Rails' built-in RJS features, but without hitting the server. For simplicity sake, let's imagine that you want to visually highlight an area of the page when a user clicks on a link, but you don't want to make a call to the server for something as simple as this. Well you can do just that using the link_to_function helper in the view.
link_to_function

link_to_function is normally used to provide a clickable link on your HTML that will call a specified JavaScript function. However it can also take a page block in exactly the same way that you use RJS templates. When the link is clicked, it will execute the JavaScript generated by the RJS block. Take this example...


‹div id="menu">Make me flash!‹/div›
‹div id="highlight_link"›
<%= link_to_function "Click me!" do |page|
page['menu'].visual_effect :highlight
page['highlight_link'].remove
end %>
‹/div›


This little snippet of code will create a link that when clicked, will highlight the menu div and then remove the actual link from the page itself. Remember: you'll need to include the Prototype library for this to work, by adding ‹%=javascript_include_tag :defaults %› in the ‹head› of your HTML page.

Obtrusive?

Some people don't like this approach, as it creates "obtrusive" JavaScript. "Obtrusive" means that the JavaScript code is mixed in with the HTML rather than being abstracted out. It, also isn't very "Railsy" using it in the view. But most of Rails' JavaScript helpers create obtrusive JavaScript, so it depends upon how puritanical you want to be. For a quick way of manipulating the DOM, this is a simple and easy time-saving method to use.

1 comment:

Alessandro Queiroz said...

wow!!!

I am looking for this for 5 days!!