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

Viewed 67037

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?

9 Answers

Native JS :

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

In rails 5 the easiest solution is to use:

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

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

pure modern js:

const onLoad = () => {
  alert("works")
}

document.addEventListener("load", onLoad)
document.addEventListener("turbolinks:load", onLoad)

with turbo it's turbo:load

Related