Rails 4: How to Use $(Document).Ready() With Turbo-Links

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

I just learned of another option for solving this problem. If you load the jquery-turbolinks gem it will bind the Rails Turbolinks events to the document.ready events so you can write your jQuery in the usual way. You just add jquery.turbolinks right after jquery in the js manifest file (by default: application.js).

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

Rather than listen to the ready event, you need to hook in to an event fired by Turbolinks for every page visit.

Unfortunately, Turbolinks 5 (which is the version that appears in Rails 5) has been re-written, and does not use the same event names as in previous versions of Turbolinks, causing the answers mentioned to fail. What works now is to listen to the turbolinks:load event like so:

$( document ).on('turbolinks:load', function() {
console.log("It works on each visit!")
})

rails 4 with turbolinks and window load

You need to initialize scripts via turbolinks. Check this ASCIIcast about turbolinks.

In general, you need to change...

jQuery(function() {
# your script
});

...to...

var ready;
ready = function() {
# your script
};

$(document).ready(ready);
$(document).on('page:load', ready);

All turbo links events you can find here.

Update for Turbolinks 5

page:load has changed to turbolinks:load, so instead you want to write:

var ready;
ready = function() {
# your script
};

$(document).on('turbolinks:load', ready);

You no longer need to specify $(document).ready(); as turbolinks:load does that. For more info, check out the README.

Rails 5: JQuery inside $(document).ready does not fire from page to page, only on reload

As I started to do more research, I found out it was a turbolinks issue.

I was able to reference this answer:

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

changing,

$( document ).ready(function() {...

to

$(document).on('turbolinks:load', function() {...

fixed all my issues.

jquery.turbolinks not working on $(document).ready in Rails

Turned out to be a simple error, I had a small script actually in the application.js file and I didn't realise that //= require turbolinks needed to go beneath that too



Related Topics



Leave a reply



Submit