Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails javascript only works after reload

The problem is exactly what the heading says. The javaScript is in the asset pipeline i.e assets/javascripts/myfile.js.coffee In the application.js I have:

//= require jquery //= require jquery_ujs //= require turbolinks //= require jquery.ui.all //= requier twitter/bootstrap //= require jasny-bootstrap //= require_tree . 

This is the coffeescript

$(document).ready ->   $("#close").click ->     $(this).parent().parent().slideUp("slow")       $( "#datepicker" ).datepicker     dateFormat : "yy-mm-dd"     player_count = $("#player option").length     $('#btn-add').click ->     $('#users option:selected').each ->       if player_count >= 8         $('#select-reserve').append("<option      value='"+$(this).val()+"'>"+$(this).text()+"</option>")         $(this).remove()           else         $('#player').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>")         $(this).remove()         player_count++     $('#btn-remove').click ->     $('#player option:selected').each ->       $('#users').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>")       $(this).remove()       player_count--     $('#btn-remove-reserve').click ->     $('#select-reserve option:selected').each ->       $('#users').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>")       $(this).remove()     $("#submit").click ->    $("select option").prop("selected", "selected") 

I can see in the source code on the browser that the javaScript has been loaded, but it only works after I reload the page.

like image 276
Jason Carty Avatar asked Jun 26 '13 10:06

Jason Carty


1 Answers

For turbolinks 5.0 you must use the turbolinks:load event, which is called the first time on page load and every time on a turbolink visit. More info: https://github.com/turbolinks/turbolinks#running-javascript-when-a-page-loads

CoffeeScript code:

$(document).on 'turbolinks:load', ->   my_func() 

JavaScript code:

document.addEventListener("turbolinks:load", function() {   my_func(); }) 
like image 187
M. Luisa Carrión Avatar answered Sep 23 '22 03:09

M. Luisa Carrión