JavaScript Check / Uncheck All Functionality

Posted on January 04, 2008
The following JavaScript will check all / uncheck all elements on the page.
function checkAll (obj) {
  var arrInput = document.getElementsByTagName("input");
  for (i=0; i<arrInput.length; i++) {
    if (arrInput[i].type == 'checkbox') {
      arrInput[i].checked = obj.checked;
    }
  }
}

Instead of multiple functions, the above code simply toggles all checkboxes.

Drop this into your html view:
<input type="checkbox" name="check_all" id="check_all" value="" onchange="checkAll(this);" /> Select / De-select All

And you have Select All / De-select all functionality.

I Can Has Less/More?

Posted on December 07, 2007

Drop the following code into your application helper and application.js for Less/More links in the style of YouTube descriptions (see to the right of any video).

In your application_helper.rb:
module ApplicationHelper

  # YouTube-style (less) ... (more) links for descriptions, etc
  def less_more(text, max=75)
    return text if text.size < max
    trimmed = truncate(text, max)
    id = rand(500000)  # 1 in 500,000 chance of collision (if using more than once per page) =)
    html = <<HTML
    <span id="#{id}-preview">#{trimmed} #{more_link(id)} </span>
    <span id="#{id}-full" style="display: none;">#{text} #{less_link(id)} </span>
HTML
    return html
  end

  def more_link(id)
    "(<a href=\"javascript:more('#{id}');\">more</a>)" 
  end

  def less_link(id)
    "(<a href=\"javascript:less('#{id}');\">less</a>)" 
  end

end
In your application.js:
function less(id) {
  Element.hide(id + '-full');
  Element.show(id + '-preview');
}

function more(id) {
  Element.hide(id + '-preview');
  Element.show(id + '-full');
}

Imports Considered Harmful

Posted on September 26, 2007
So in your layout you have something like this:
<%= stylesheet_link_tag 'main' %>

Then in your main.css you have something like:

@import "interface.css"; /* element level style */
@import "style_class.css"; /* class level style */

The problem is—how do browsers know to request a fresh copy of the imported CSS files whenever they change. When you use Rails’ helpers, an etag gets appended on the end of the requests. (that’s the ?13232352 you see on the end of rails-generated asset URLs)

Instead of using CSS @import directives, just use the rails helpers or a system like Asset Packager to group all CSS into a single file and force a download on any css change.