AdamNYC AdamNYC - 4 months ago 14
Ruby Question

Making jQuery works with Turbolinks

I have a Rails 4 app, which uses

Turbolinks
. My understanding is that
Turbolinks
breaks jQuery code, as Turbolinks does not load new page, but only get new elements.

Therefore, navigating to new page may not trigger
.ready
, although it always triggers
.page:load
, and thus new jQuery code won't initialize.

I have a lot of jQuery code, so I don't want to modify my jQuery code to be compatible with Turbolinks.

Is it possible to add a javascript code to my application.js that overwrites
.ready
event to include
page:load
as well? How should I do it?

Answer

Rather than wait for $(document).ready to fire for your jQuery, just use page:load instead:

$(document).on 'page:load' ->
  <your code>

Alternatively, you can set up the jquery.turbolinks gem: https://github.com/kossnocorp/jquery.turbolinks

Comments