Rails 5: How to Use $(Document).Ready() with Turbo-Links

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: 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: 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.

$(document).ready doesn't fire when navigating to a new page

I believe this is related to turbolinks, the page doesn't actually reload, so you need to run your code through a different event:
Rails 5: how to use $(document).ready() with turbo-links



Related Topics



Leave a reply



Submit