August 10, 2014 · rails turbolinks

Rails Turbolinks with Fancybox 2

Obviously you are familiar with gem turbolinks that going out of the box in rails. So it’s quite cool to use it for not very complicated tasks. For example I use it in one of the projects for Ajax pagination. I simply use kaminari and turbolinks doing all dirty job for me, without any javascript from my part. But it has a problem with binding events to DOM-elements. For example today I spent approximately an hour for brings fancybox plugin to work properly with turbolinks. The problem is that the content of the page loaded dynamically via Ajax and our DOM-events don't apply to it.

Actually the problem is generic for Ajax-loaded content. And the general solution in javascript is bind events to document, like this:

$(document).on('click', function() {
  // some stuff here

In case of fancybox the default code from documentation for use plugin is this:


But it will not work with turbolinks properly. Your image link will be not clickable after each page Ajax-reloading. So, after some researches I found very simple solution for this:

$('a.fancybox').fancybox(parent: 'body');

It will define body as a parent element for the container. And your links to images will work properly even with turbolinks.

Recommended gems