La Murga
La Murga

Reputation: 303

.js file only loads after refreshing the page in rails

I have the following JavaScript code on a rails project

// app/assets/javascript/simple_effects.js

$(function() {
  // Hide completed tasks when checkbox is clicked. projects/show
  $('#hide-completed').click(function() {
    $('.task-completed').toggle();
  });
  // Change label to checkbox that hides completed tasks. project/show
  $('#hide-completed').change(function(){
    var c = this.checked ? ' Show completed tasks' : ' Hide completed tasks';
    $('#checkbox-label').text(c);
  });

});

The code does not trigger when I enter the page but only after refreshing it. I am using turbolinks.

I am aware of this question: Rails loading my javascript only after a page reload But I don't really know if that solution can be used in my case as well. Thank you!

Edit: This is my application.js file

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .

Upvotes: 0

Views: 1194

Answers (2)

SimonH
SimonH

Reputation: 1425

If you're using turbolinks 5+, jquery-turbolinks doesn't work anymore (see https://github.com/kossnocorp/jquery.turbolinks).

Instead you can wrap your code into the function $(document).on "turbolinks:load", ->.

E.g.

$ ->
  $("#add-artwork-btn").on 'click', ->
    div = $("#add-artwork-div")
    div.toggle(200)

becomes to

$(document).on "turbolinks:load", ->
  $ ->
    $("#add-artwork-btn").on 'click', ->
      div = $("#add-artwork-div")
      div.toggle(200)

Upvotes: 0

mohameddiaa27
mohameddiaa27

Reputation: 3597

If you have a lot of existing JavaScript that binds elements on jQuery.ready(), you can pull the jquery.turbolinks library into your project that will trigger ready() when Turbolinks triggers the the page:load event. It may restore functionality of some libraries.

Add the gem to your project,

gem 'jquery-turbolinks'

then add the following line to your JavaScript manifest file, after jquery.js but before turbolinks.js:

//= require jquery.turbolinks

your application.js

//= require jquery
//= require jquery_ujs
//= require jquery.turbolinks
//= require turbolinks
//= require bootstrap-sprockets
//= require_tree .

Upvotes: 5

Related Questions