1

I'm a beginner of Ruby on Rails and jQuery.

I made a homepage based on template (https://html5up.net/massively).

It has many pages and linked each other through the nav bar.

I changed and added my things on the template but jQuery does not work consistently, unlike the site.

When refresh, it works at the first.

But when I move to another page in my project by click, it does not work before refreshing.

I cannot read and understand the code 100% in the template, but I guess this line (in main js file) is directly related to the problem.

$(function() {

    var $window = $(window),
        $body = $('body'),
    ---omitted---

    // Disable animations/transitions until the page has loaded.
        $window.on('load', function() {
            window.setTimeout(function() {
                $body.removeClass('is-loading');
            }, 100);
        });

    ---omitted---

All html codes of all pages start with

<body class="is-loading">

How can I make jQuery works consistently while moving pages, without refresh?

Sieun Sim
  • 71
  • 5

1 Answers1

0

It is probably related to Turbolinks, which means that window onload does not fire in subsequent page transitions.

According to https://stackoverflow.com/a/18770589/483133 for Rails 5:

For Rails 5 (Turbolinks 5) page:load becomes turbolinks:load and will be even fired on initial load. So we can just do the following:

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

  ...your javascript goes here...

});
Phil
  • 2,797
  • 1
  • 24
  • 30
  • Thanks a lot! Can I ask one more question? The template's javascript uses (function($){})(jQuery); instead of $(document).... In this case, How can I add 'turbolinks:load' ? – Sieun Sim Dec 18 '17 at 14:01
  • `(function($) { })(jQuery);` is just a pattern that runs function in the curly brackets immediately. Typically for jQuery templates, this encapsulates the code inside the curly brackets, and allows the use of the commonly used `$` syntax for calling jQuery functions, even if `$` is used outside for something else. You need to look for the actual function inside that runs when the DOM is loaded or ready. Calling it from the `turbolinks:load` event handler might just work if you put that alongside it. I suggest trying, then if you have issues to post a new question with some sample code. – Phil Dec 18 '17 at 14:27
  • One other thing I meant to say... if your template is highly dependent on JQuery and/or Javascript for operation, is a single page app, uses a lot of Ajax to update the page, or is reactive, you may want to consider removing Turbolinks from your project completely. That way you can just rely on your template in its native form. Here is one approach: http://blog.steveklabnik.com/posts/2013-06-25-removing-turbolinks-from-rails-4 – Phil Dec 19 '17 at 16:52
  • it finally works after removing the turbolinks gem. Thanks a lot :) – Sieun Sim Feb 10 '18 at 08:40