T.Kiril
T.Kiril

Reputation: 61

Rails turbolinks issues with window.onload

I have rails application with baguetteBox library for image popup effect, but it works properly only after page refresh. I know that its because of turbolinks so I installed jquery-turbolinks gem but it still doesn't work. //require jquery.turbolinks is in the right spot.

  //
  //= require jquery
  //= require jquery.turbolinks
  //= require jquery_ujs
  //= require baguetteBox.min
  //= require turbolinks
  //= require_tree .

And i have this piece of code in the bottom of show view

<script>
   window.onload = function() {
   baguetteBox.run('.step_div');
   };
</script>

to initialize the script.

Any ideas?

Upvotes: 1

Views: 4467

Answers (1)

Jon
Jon

Reputation: 10898

You need to trigger things slightly differently for turbolinks:

var myFunc = function() {
  baguetteBox.run('.step_div');
};

$(document).ready(myFunc);
$(document).on('page:load', myFunc); // Classic Turbolinks
$(document).on('turbolinks:load', myFunc); // Turbolinks 5

This way, your function will be called on a standard page ready trigger, and also when turbolinks loads the page into memory without an actual page refresh. Obviously, you only need to include the turbolinks event trigger for the appropriate version of turbolinks that you're using.

Have a look here for the other events triggered by turbolinks 5: https://github.com/turbolinks/turbolinks#full-list-of-events

For the original turbolinks, the documentation is here: https://github.com/rails/turbolinks/#events

Upvotes: 15

Related Questions