drewwyatt
drewwyatt

Reputation: 6027

JS in Rails App only loads the first time

I am using a fade effect on some links on my applications home page. This is being accomplished by some JQuery:

javascripts/pages.js

$(document).ready(function() {
    $('.home_tile_text').hide().removeClass('text').addClass('text-js');
    $('.home_tile_overlay').hide().removeClass('overlay').addClass('overlay-js');

    $('.home_tile').mouseenter(function(){
        $(this).find('.text-js').finish().hide().fadeIn();
         $(this).find('.overlay-js').finish().hide().fadeIn();
    });
    $('.home_tile').mouseleave(function(){
        $(this).find('.text-js').finish().show().fadeOut();
         $(this).find('.overlay-js').finish().show().fadeOut();
    });
});

This all works great when I fire up the app for the first time. However, if I navigate away from the home page, when I come back, the fade effect no longer works until I "refresh" the page. Any ideas?

Upvotes: 3

Views: 845

Answers (1)

Dylan Karr
Dylan Karr

Reputation: 3564

This is probably because of Rails 4's new feature Turbolinks. Turbolinks reduces server requests from the client by only updating the parts of the page that change. This means that document.ready (or $(document).ready in jQuery) doesn't get called again when loading new pages.

One solutions is to just remove the gem 'turbolinks' in your gemfile and require turbolinks in your application.js, thereby disabling turbolinks, but an easier fix is to just add require jquery.turbolinks in the application.js file which includes a turbolinks script that patches the problem by calling $(document).ready on every turbolinks call.

For more, refer to the jQuery section in the turbolinks readme.

Upvotes: 5

Related Questions