javascript “more” and “less” links to show and hide big chunks of text, in rails

you know those “more” and “less” links on websites that show more and less text if you click on a more or less link? those are kinda useful to help pages with lots of content scale gracefully.

here’s a rails helper that let’s you do exactly that. take it, tweak it. make the code prettier because it certainly isn’t right now.

module ApplicationHelper
  def truncated_text text, length = 40
    words = text.split
 
    # not enough words?  just spit back the input.
    return text  if words.length < = length
 
    # generate a random dom id
    # String.random(n) is roughly: UUID.random_create.to_s.gsub('-', '')[1..n]
    id = 'truncated_' + String.random(8)
 
    #
    # the whole thing, as a big concatenated string
    #
    words[0 .. length].join(' ') + ' ' +
 
    # the "more..." link
    link_to_function('more...', :id => id + '_more') do |page|
      page < < "$('#{id}').removeClassName('hidden')"
      page << "$('#{id}_more').hide()"
    end +
 
    #
    # span containing the remainder text and the "less..." link
    #
    "<span id="#{id}" class="hidden">" +
 
    # the text that appears after clicking the "more..." link
    words[length + 1 .. -1].join(' ') + ' ' +
 
    # the "less..." link to hide the text that the "more..." link exposed
    link_to_function('less...', :id =>; id + '_less') do |page|
      page < < "$('#{id}').addClassName('hidden')"
      page << "$('#{id}_more').show()"
    end +
 
    '</span>'
  end
end

use it thusly in your views.

  < %= truncated_text content.description %>

remember to define a hidden class in your stylesheet! (.hidden { display: none }). so, exercises for the reader? customizable more/less links. maybe some scriptaculous effects? efficiency?

note that copying/pasting this into your code isn’t gonna work because wordpress mangles some of the ruby syntax. so you need to fix that stuff up a tiny bit. but then you’re good. who can tell me how to fix wordpress to not be retarded about code?


About this entry