Menu icon Foundation
JavaScript not working on Ruby on Rails

The JavaScript elements aren't working across site even though they're being loaded. Is there a solution for fixing this issue for Ruby on Rails?

//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require foundation
//= require turbolinks
//= require_tree .

$(function () {
$(document).foundation();
});

The JavaScript elements aren't working across site even though they're being loaded. Is there a solution for fixing this issue for Ruby on Rails?

//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require foundation
//= require turbolinks
//= require_tree .

$(function () {
$(document).foundation();
});

javascriptruby on rails 4rubyturbolinks

The JavaScript elements aren't working across site even though they're being loaded. Is there a solution for fixing this issue for Ruby on Rails?

//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require foundation
//= require turbolinks
//= require_tree .

$(function () {
$(document).foundation();
});

The JavaScript elements aren't working across site even though they're being loaded. Is there a solution for fixing this issue for Ruby on Rails?

//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require foundation
//= require turbolinks
//= require_tree .

$(function () {
$(document).foundation();
});

Yanik Crépeau over 2 years ago

It is a jQuery + Foundation -vs- Turbolinks conflicts.

Turbolinks makes all your internal links (jumping from one page to another in your own site) a little bit special. When you click on an internal link, instead of reloading the entire page, only the part between the <body>...</body> is actually loaded. All the CSS or Javascript stuff remains in place. That makes jumping from one section to another very very fast.

The setback, the jQuery event "a new page has just loaded" is NOT triggered when you jump from one section to another.

The is no magic tricks to solve that issue. However, I suggest the following solution to alleviate your issue:

Create a file named /app/assets/javascripts/foundation.coffee

Add the following code:

setup = ->

  $(document).foundation();

$ ->

  console.log "Loading page...!  " + Date.now()%10000

  setup()

  document.addEventListener "turbolinks:load", () ->

    console.log "turbolinks:load "  + Date.now()%10000

    setup()

 

------------------

The setup function calls the foundation initializer.

 

setup() is called when a page is loaded.

When a page is loaded, a listener is set to call setup() when a "turbolinks:load" event is trigged. 

The console.log add a print out helping you to test how it works. You can remove the console.log messages when you're ready.