Search code examples
jqueryruby-on-railsturbolinks

How to write jQuery code properly in Rails 5 (with turbolinks 5)


I'm writing jQuery code in my Rails 5 app and it looks like code isn't compiling. This is my code:

application.html.erb

 <%= content_for?(:head) ? yield(:head) : '' %>
    <%= javascript_include_tag "application" %>
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag "//www.google.com/jsapi", "chartkick" %>

application.js

//= require code.js
//= require jquery
//= require fancybox
//= require jquery_ujs
//= require jquery.turbolinks
//= require turbolinks
//= require bootstrap-sprockets
//= require bootstrap
//= require_tree .
$.turbo.use('turbolinks:load', 'turbolinks:request-start')

function printpage()
{
   window.print()
}

var resetForms = function () {
  // this depends on your use
  // this is for foundation 6's abide
  $('form').each(function () {
    $(this).foundation('destroy');
  });
};

document.addEventListener("turbolinks:before-cache", function() {
  resetForms();
});

When I try to use $(document).ready(function(){}); in code.js it just doesn't work, but when I try something like this:

document.addEventListener("turbolinks:load", function() {
 alert("ok!")
});

It works with no problems. I don't understand why code work with other versions of Rails, doesn't work this time. In addition I can say that my app is using turbolinks in version number 5


Solution

  • $(document).ready(function() {
      resetForms();
    });
    

    This will not work because Turbolinks overrides the normal page loading process, the event that this relies on will not be fired. If you have code that looks like this, you must change your code to do this instead:

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

    If it worked with another version of rails, it was probably using an older version of turbolinks.

    http://guides.rubyonrails.org/working_with_javascript_in_rails.html#turbolinks [1]