Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Turbolinks prevents normal $(document).ready() events from firing on all page visits besides the initial load, as discussed here and here. None of the solutions in the linked answers work with Rails 5, though. How can I run code on each page visit like in prior versions?

like image 276
AndrewH Avatar asked Mar 20 '16 06:03

AndrewH


3 Answers

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!")
})
like image 158
AndrewH Avatar answered Nov 07 '22 00:11

AndrewH


Native JS :

document.addEventListener("turbolinks:load", function() {
    console.log('It works on each visit!');
});
like image 45
Siamko Avatar answered Nov 06 '22 22:11

Siamko


In rails 5 the easiest solution is to use:

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

Instead of $(document).ready. Works like a charm.

like image 13
Milad.Nozari Avatar answered Nov 06 '22 22:11

Milad.Nozari