Question

What is the best way to create a hide and show effect in rails 2. Is it to use a JQuery type solution or is there something as good, better or easier built in?

Was it helpful?

Solution

The easiest way is to use link_to_function in the view:

<%= javascript_include_tag :defaults %>

<%= link_to_function "toggle", "$('thing_#{@thing.id}').toggle()" %>

<p id="thing_<%= @thing.id %>">
  <b>Body:</b>
  <%=h @thing.body %>
</p>

Another way to do it is to use RJS, but it depends a lot on how your application. That way you'd have to set up your controller to look for either custom actions outside of the RESTful actions, or have the exisiting actions look for XHR requests (using "if request.xhr?")

The RJS is pretty easy:

page["thing_#{@thing.id}"].toggle

Personally, I'd say that anything more than $(element).toggle() deserves to be outside the view into it's own RJS, since the view is supposed to be mostly free of logic, but probably there's a lot of differing opinions on that.

As for the javascript framework, unless I am doing something really that requires something that isn't available in prototype/scriptaculous, I'll just stick with the defaults for simplicity.

OTHER TIPS

Rails comes with Prototype/Scriptaculous javascript libraries bundled, but it's up to you if you want to use them. In the end you have to use Javascript of some kind, there's nothing special built-in to Rails that will magically do this for you.

I personally recommend jQuery -- I've found it's faster to learn and more powerful and extendable.

$('#elementid').hide();
$('#elementid').show();
$('.elementClassname').show();
$('.elementClassname').hide();

You can give parameters as well like

$('.elementClassname').show('slow');
$('.elementClassname').show('normal');
$('.elementClassname').show('fast);

or Numeric value as well

$('.elementClassname').show(600);

You an use toggle as well

$('.elementClassname').slideToggle();

JQuery is an excellent choice, regardless of the platform, works just as well on Ruby as it does with ASP.NET/MVC

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top