0

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 .
1
  • can you post your application.js file ? Commented Nov 2, 2014 at 0:42

2 Answers 2

5

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 .
Sign up to request clarification or add additional context in comments.

3 Comments

The application throws an error: couldn't find file 'jquery.turbolinks'
You must restart your rails server after adding this gem. Otherwise you get the error La Murga got.
Note that this does not work with turbolinks 5+, as noted on their github page: github.com/kossnocorp/jquery.turbolinks
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.