user1636937 user1636937 - 1 year ago 51
jQuery Question

jQuery works and doesn't work when it first loads

I have a rails app that I'm trying to implement some jQuery in.

I have two scripts, one that works on first load, and one that requires a reload. I had a problem with the one that works now where I modified the turbolinks in application.js. Now the same problem is happening to another script.

The one that works:

//set animation timing
var animationDelay = 5000,
//loading bar effect
barAnimationDelay = 3800,
barWaiting = barAnimationDelay - 3000, //3000 is the duration of the transition on the loading bar - set in the scss/css file
//letters effect
lettersDelay = 50,
//type effect
typeLettersDelay = 150,
selectionDuration = 500,
typeAnimationDelay = selectionDuration + 800,
//clip effect
revealDuration = 600,
revealAnimationDelay = 1500;


The one that doesn't work:

//if you change this breakpoint in the style.css file (or _layout.scss if you use SASS), don't forget to update this value as well
var MQL = 1170;

//primary navigation slide-in effect
if($(window).width() > MQL) {
var headerHeight = $('.box-header').height();
previousTop: 0

so on so forth.

Why is this happening? Is there a problem with the CSS or the page in which it's being called?

Answer Source

Turbolinks can cause problems in your Rails app because it tries to save overhead by maintaining assets listed in the <head> element of your page (among other things). When you load a page using a full load (via refresh button), an actual ready event takes place and your scripts work. On the other hand, if you were to visit a page some other way (via link), Turbolinks tries to reuse the <head> element, so there's no ready event fired.

The solution in the past was to simply disable Turbolinks, either entirely, by removing its require line in application.js or by link (data: {no_turbolink: true}). With Rails 4.2.x and 5.x, you can listen for a Turbolinks related event that should work where a normal ready event would have worked before.

From the documentation:

However, 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

$(document).ready ->
  alert "page has loaded!"

you must change your code to do this instead:

$(document).on "turbolinks:load", ->
  alert "page has loaded!"

(quote rearranged slightly for clarity)