Rails 4: how to use $(document).ready() with turbo-links

I ran into an issue in my Rails 4 app while trying to organize JS files “the rails way”. They were previously scattered across different views. I organized them into separate files and compile them with the assets pipeline. However, I just learned that jQuery’s “ready” event doesn’t fire on subsequent clicks when turbo-linking is turned on. The first time you load a page it works. But when you click a link, anything inside the ready( function($) { won’t get executed (because the page doesn’t actually load again). Good explanation: here.

So my question is: What is the right way to ensure that jQuery events work properly while turbo-links are on? Do you wrap the scripts in a Rails-specific listener? Or maybe rails has some magic that makes it unnecessary? The docs are a bit vague on how this should work, especially with respect to loading multiple files via the manifest(s) like application.js.

19 Answers
19

Leave a Comment