Fancybox is a really neat little lightbox alternative. Integrating Fancybox into your rails application is easy thanks to the fancybox-rails and fancybox2-rails gems. This article will show you how to integrate fancybox with your rails application.

The original fancybox is free to use in both commercial and non commercial settings, however please note that you can only use Fancybox 2 in a commercial environment if you have purchased it. You can purchase Fancybox 2 from the FancyApps site at http://fancyapps.com/fancybox/.

Okay, lets get started. First we need to add the fancybox and/or fancybox2 gem to our gemfile. Please note that you will also need jquery installed in order for fancybox/fancybox2 to function. Most recent versions of Rails include this, so we won't go over how to install it here.

Gemfile (for Fancybox):

gem 'fancybox-rails'
Gemfile (for Fancybox 2):

gem 'fancybox2-rails'

Now run a bundle install.

Terminal Commands:

bundle install

Please note that the remaining steps are the same for both fancybox and fancybox2.

Next, open the application.js file and add the following line underneath the //=require jquery line.

app/assets/javascripts/application.js:

//= require fancybox

Now, add the following line to your application.css file. It should go undernearth the *= require_self line.

app/assets/stylesheets/application.css:

*= require fancybox

Great, now lets create an example controller so that we can play with the fancybox functionality. Run the command below to create a controller called Example.

Terminal Commands:

rails g controller Example show

Now, lets edit the routes file and add a couple things to get our example controller to work. Open your routes file and add the following code.

config/routes.rb:

resource :example, only: [:show], controller: :example
root to: "example#show"

Great, now that we are set up, lets edit our show view for the example controller so that we can start to play with Fancybox. Open the show view for the Example controller and add in the code listed below.

app/views/example/show.html.erb:

<%= link_to "Show mah Fancybox!", "#hello", class: "fancybox" %>

<div style="display:none;">
  <div id="hello">
  Hello world!
  </div>
</div>

Great, now lets add the final piece of code to make everything work. Open up your application.js file again and add the following code.

app/assets/javascripts/application.js:

$(document).ready(function() {
  $("a.fancybox").fancybox();
});

Great! Now if you fire up and navigate to your rails development server you will see a link. If you click on that link you will get a Fancybox lightbox popup. That's it! Thanks for reading. Below are some links to help you out with things like customizing fancybox and the like. Enjoy!

Resources