Home >Web Front-end >JS Tutorial >How to Use $(document).ready() with Turbo Links in Rails 4 and 5?
In Rails 4, it's common to organize JavaScript files into separate entities and compile them using the assets pipeline. However, using jQuery's "ready" event may pose challenges when turbo-links are enabled. As turbo-linking avoids full page reloads, subsequent page clicks prevent the execution of code within the "ready" function.
Solution:
To ensure proper functioning of jQuery events with turbo-links, utilize the following approach:
CoffeeScript:
ready = -> ...your coffeescript goes here... $(document).ready(ready) $(document).on('page:load', ready)
Here, the additional line listens for the 'page:load' event, triggered by turbo-links.
JavaScript:
var ready; ready = function() { ...your javascript goes here... }; $(document).ready(ready); $(document).on('page:load', ready);
Alternative for Rails 5 (Turbolinks 5):
Rails 5 introduces a new event 'turbolinks:load' that's fired on both initial and subsequent page loads. This allows us to simplify the solution:
$(document).on('turbolinks:load', function() { ...your javascript goes here... });
This approach ensures that jQuery events fire as expected when turbo-links is active, allowing for smooth operation of JavaScript functionalities on your Rails 4 application.
The above is the detailed content of How to Use $(document).ready() with Turbo Links in Rails 4 and 5?. For more information, please follow other related articles on the PHP Chinese website!