Dynamic sections

by Herb on 4 June 2007

One way to deal with displaying alot of content is using dynamically expanding/collapsing sections. AJAX blind effects like those seen in Gmail make this a popular option these days. Rails includes a thorough javascript library which among others includes the Prototype libray. Drop the following on any page requiring javascript functions (or simply in the application layout to make them avaliable everywhere).

< %= javascript_include_tag  :defaults %>

With the Rails framework in mind the logical step would be to construct a helper to spit out and manipulate the divs on the page. The only relevant post I found was rather old, however gave me what I needed to start off with.

Helper code (I stored it in application_helper.rb):

  # Dynamic expand/collapse
  def toggle_display_links(field_id)
    # Inserts HTML for 2 spans, for expanding/collapsing div on the page
    html_for_output = "<span id='#{field_id}Expand'>\n"
    html_for_output < < "<img src='/images/arrow_down.gif'
	onclick=\"Element.show('#{field_id}'); Element.toggle('#{field_id}Expand','#{field_id}Collapse'); return false;\">\n"
    html_for_output < < "</span>\n"
    html_for_output < < "<span id='#{field_id}Collapse'>\n"
    html_for_output < < "<img src='/images/arrow_up.gif' 
	onclick=\"Element.hide('#{field_id}'); Element.toggle('#{field_id}Expand','#{field_id}Collapse'); return false;\">\n"
    html_for_output < < "</span>\n"
 
    html_for_output
  end
  def toggle_display_hide(field_id)
    # Hides by default
    javascript_tag("Element.hide('#{field_id}Expand')")
  end
</span>

For your view:

< %= toggle_display_links("oper") %>
<div id="oper"></div>
< %= toggle_display_hide("oper") %>

This results in a simple arrow button (any two images can be used) which can be toggled by clicking on it. In this case I was trying to maximize performance of the site, however this can be easily modified to feature the AJAX blind effect.

To use AJAX and animate the expansion/collapse:

onclick=\"Effect.BlindDown('#{field_id}');
 
onclick=\"Effect.Blindup('#{field_id}');

Leave a Comment

Previous post:

Next post: