Search code examples
jqueryruby-on-railsturbolinks

Turbolinks & Ladda


I'm trying to use Turbolinks 3.0 and Ladda together in a Rails application. The ladda documentation states:

"If you will be using the loading animation for a form that is submitted to the server (always resulting in a page reload) you can use the bind() method"

Which is what I was doing before I implemented Turbolinks. Turbolinks works automatically for most simple get requests, but for form submissions, I'm switching my forms to remote and just rendering the main div of my page back as shown on the readme. This works great in general.

However, if the user hits the back button after doing that, the ladda button is still left in its disabled, greyed, and loader image state. I don't want to rely on a timer.

Since I'm not reloading the page as stated in the quote above, I was trying to activate Ladda without the bind method. But the only other way I can think of doing it would be to activate Ladda on an onclick.

But for some reason, if I bind an onclick to the submit button, it breaks turbolinks, and the form isn't submitted at all.

$(document).on('click', '.ladda-button', function() {
  $(this).ladda('start');
});

That will activate ladda, but then the form isn't submitted. I'm using jquery-turbolinks, so that code should work?

The other direction would be to keep using Ladda through the bind method, and then reset any ladda images before a page is "loaded" through Turbolinks. I accomplished this as follows:

$(document).on("page:before-unload", function() {
  $(".ladda-button").ladda();
  $(".ladda-button").ladda("stop");
});

If I put a breakpoint there in the debugger, I can see that this successfully resets the button to its original state right before the next page is loaded through Turbolinks. But when I hit back, the loader is back to its deactivated/grey/loading state.

I don't wanna re-write my whole app as a client-side javascript MVC and an API backend, but I really want it to have a snappy, no-page-refresh feel to it - and use those awesome ladda loading images as well. Turbolinks 3.0 is awesome so far, but I'm really stumped on this one.

Any help would be greatly appreciated!

EDIT: I'm just now realizing that all of my JS is broken if the user hits back.


Solution

  • There was a bigger issue here - no scripts were getting run when pressing back or forward. The loader was just the first I noticed.

    A workaround/fix was implemented here: https://github.com/rails/turbolinks/pull/509

    You need to use "data-turbolinks-eval=true" on your script tag to have the JS fire even if its a page back/forward.

    Then just re-initialize the ladda/loading image there.

    <script data-turbolinks-eval=always>
      $(".ladda-button").ladda();
      $(".ladda-button").ladda('stop');
      $(".ladda-button").ladda('bind');
    </script>