Home > Web Front-end > JS Tutorial > How to Use $(document).ready() with Turbo Links in Rails 4 and 5?

How to Use $(document).ready() with Turbo Links in Rails 4 and 5?

DDD
Release: 2024-12-13 17:47:10
Original
225 people have browsed it

How to Use $(document).ready() with Turbo Links in Rails 4 and 5?

Utilizing $(document).ready() with Turbo-Links in Rails 4

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)
Copy after login

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);
Copy after login

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...

});
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template