Friday, August 14, 2009

Lightbox for Rails

   There are plugins available that will create a lightbox effect for you, but in each case I ran into problems adapting the plugin to my needs. I'm going to share with you the steps I took to introduce my own lightbox effect that has proven to be extremely flexible and easy to use.

Gray Out
   The first thing we need is the gray-out effect. I did a little searching and found a javascript function, grayOut, that has worked out really nicely. The code has some useful comments for explaining the various options it accepts, so I won't go into the details.
   Paste this code into your application.js file to ensure it will be available by default in all your layouts (assuming you are using the javascript_tag :defaults option)

HTML/CSS
   The next thing we need is an HTML container to hold the lightbox and some CSS to style it so it should show up center screen. Here are the steps:
  1. somewhere inside the body tag add an empty div tag with class "lightbox" and id "lightboxContainer and the style set to "display:none" inline.
  2. in default.css add the lightbox class: .lightbox{position:absolute; z-index:1000; width: 100%; margin: 0 auto; top: 50px}. The top should be adjusted to whatever fits your site template best.
Rails
   Finally we write some rjs code to display content in a lightbox. I like to use helpers for commonly used rjs code. This has proven really useful in keeping the controllers DRY. In whatever helper you wish (since helpers are global) create the following method:

def display_lightbox(partial)
  page << "grayOut(true, {'z-index':'25','opacity':'50'});"
  page['lightboxContainer'].show
  page['lightboxContainer'].replace_html(render(:partial=>partial))
end

Now in your controller to display a lightbox in response to a js request (ajax), you only need a single line of code inside your render block to display the lightbox. Example:

respond_to do |format|
  format.js do
    render :update do |page|
      page.display_lightbox("/[controller_views_directory]/some_partial")
    end
  end
end

And that's all there is to it. I went a couple steps further in my project to allow stacking n number of lightboxes that are managed by a javascript class. If I get enough requests I may post that as well.

1 comment: