Search code examples
javascriptjqueryruby-on-railsruby-on-rails-5turbolinks

In Rails, jQuery objects disappear after pageload, reappear on refresh


I have some custom jQuery code creating the frontend for a business optimisation machine.

simutronX.js

$(function(){
    $("#slider_constraint_a").slider({
    orientation: "vertical",
    range: true,
    values: [17, 67],
    slide: function(event, ui) {
      $("#constraint_a").val(ui.values[0] + " - " + ui.values[1]);
      }
    });
    $("#constraint_a").val($("#slider_constraint_a").slider("values", 0) +
      " - " + $("#slider_constraint_a").slider("values", 1));

    ...

    $("#slider_constraint_e").slider({
    orientation: "vertical",
    range: true,
    values: [17, 67],
    slide: function(event, ui) {
      $("#constraint_e").val( ui.values[0] + " - " + ui.values[1] );
      }
    });
    $("#constraint_e").val( $("#slider_constraint_e").slider("values", 0) +
      " - " + $("#slider_constraint_e").slider("values", 1));
});

When the page loads, the constraint sliders appear very briefly, then disappear. On refresh, these items reappear. I have gem installed the jquery-turbolinks gem as suggested here and added it to my application.js file, then precompiled the assets and restarted the server.

application.js

//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require jquery-ui

This does not seem to have helped. A similar problem is listed in the jquery-turbolinks readme (e.g. double loading...) but it doesn't appear my code has any of the problems listed.

Any further suggestions?


Solution

  • I had this issue previously. Solution was to surround the Jquery code with a on change action rather than on load action in your js file

     $(document).on('page:change', function(){