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
What Is the Most Efficient Way to Reverse an Array in JavaScript
How to Auto-Slide the Window Out from Behind Keyboard When Textinput Has Focus
Check If Element Is Visible on Screen
How to Create an Auto-Complete Combobox
React Routing Works in Local MAChine But Not Heroku
JavaScript String Array to Object
How to Show a Spinner While Loading an Image via JavaScript
Why Are Es6 Classes Not Hoisted
Jquery Returning "Parsererror" for Ajax Request
JavaScript Timestamp to Relative Time
Javascript: Dynamically Creating Variables for Loops
How Variables Are Allocated Memory in JavaScript
How to Bind Bootstrap Popover on Dynamic Elements
Removing Duplicate Objects with Underscore for JavaScript
How to Pass Data from Child to Parent Component Angular