0

I have a javascript file called "front.js" i load from "application.js" like usual with this code:

//= require front

Inside "front.js",i have many functions i want to launch when the document is ready like this:

$(document).ready(function() {
  $("#test").click(function(event){
    ...
  });
});

But the problem is "front.js" is loaded only when i refresh the page manually (ctrl+r / f5 ) and not when i move from page to page, so my javascript code cannot be executed as wanted. Maybe this comes from turbolinks, i dont know how to handle this issue. When i put scripts directly in the html files, it works but it's definitely not the right thing to do.

Can anyone help me on this please ?

dzof31
  • 1,423
  • 1
  • 12
  • 20
  • possible duplicate of [Rails 4: how to use $(document).ready() with turbo-links](http://stackoverflow.com/questions/18770517/rails-4-how-to-use-document-ready-with-turbo-links) – Roman Kiselenko Apr 30 '14 at 09:48
  • Actually i didn't know if this problem came from Turbolinks or not. – dzof31 May 05 '14 at 12:35

3 Answers3

3

There are three ways by which you can do it.

a. You can wrap your jquery code inside a function and then call that function on page load. If your function is ready then you can do:

$(document).ready(ready);
$(document).on('page:load', ready);

b. You can use jquery's live event or "on" event:

$(document).on("click","#test",function(){
 // your code
});

c. You can use the jquery-turbolinks gem which will bind the Rails Turbolink events to the document.ready events so you can write your jQuery in the usual way. For more information refer to here

Community
  • 1
  • 1
Mandeep
  • 9,093
  • 2
  • 26
  • 36
2

It's due to turbolinks, do this instead

var ready;
ready = function() {
  $("#test").click(function(event){
    ...
  });
};
$(document).ready(ready);
$(document).on('page:load', ready);
Rajdeep Singh
  • 17,621
  • 6
  • 53
  • 78
1

I had the same problem when using foundation in my project, you can disable turoblinks by not requiring turbolinks in your application.js file and it should solve the problem.

Andrew_tainton
  • 261
  • 1
  • 3
  • 13
  • Also be sure to take out references to turbolinks in places like application.html.erb. Do a recursive grep search on your project to be sure you rip out all traces of of that "feature," and your JS may start working normally. – JosephK Nov 24 '15 at 09:23