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
$(Document).Ready Equivalent Without Jquery
Persist Variables Between Page Loads
How to Merge Two Arrays in JavaScript and De-Duplicate Items
Why Does Calling React Setstate Method Not Mutate the State Immediately
Abort Ajax Requests Using Jquery
Iterate Through Object Properties
Aren't Promises Just Callbacks
How to Convert an Image into Base64 String Using JavaScript
How to Sort an Array of Integers Correctly
How to Detect Safari, Chrome, Ie, Firefox and Opera Browsers
How to Execute a JavaScript Function When I Have Its Name as a String
Getting a Random Value from a JavaScript Array
Share Data Between Angularjs Controllers