Script coffee does not work when changing a page, but it works when a page loads. [Rails 5]

I use a coffee script in my rails project, but the problem is that it only works when I load (refresh) a page, and when the page is displayed, it should also work on changing the appearance of the page.

here is the script i use:

facebook.js.coffee

jQuery -> $('body').prepend('<div id="fb-root"></div>') $.ajax url: "#{window.location.protocol}//connect.facebook.net/en_US/all.js" dataType: 'script' cache: true window.fbAsyncInit = -> FB.init(appId: env["app_id"], cookie: true) $('#sign_in').click (e) -> e.preventDefault() FB.login (response) -> window.location = '/auth/facebook/callback' if response.authResponse $('#sign_out').click (e) -> FB.getLoginStatus (response) -> FB.logout() if response.authResponse true 
+7
javascript jquery ruby-on-rails coffeescript
source share
2 answers

you can try "turoblinks:load"

 ready = -> $('body').prepend('<div id="fb-root"></div>') $.ajax url: "#{window.location.protocol}//connect.facebook.net/en_US/all.js" dataType: 'script' cache: true window.fbAsyncInit = -> FB.init(appId: env["app_id"], cookie: true) $('#sign_in').click (e) -> e.preventDefault() FB.login (response) -> window.location = '/auth/facebook/callback' if response.authResponse $('#sign_out').click (e) -> FB.getLoginStatus (response) -> FB.logout() if response.authResponse true $(document).on('turbolinks:load', ready) 
+4
source share

https://github.com/turbolinks/turbolinks#running-javascript-when-a-page-loads

 document.addEventListener("turbolinks:load", function() { // ... }) 
0
source share

All Articles