'$(document).ready does not work in Rails

I'm using a *.js.erb in my Rails-App, which reacts to a clicked Link. But when I render my page, by getting there via a link_to, I have to refresh the Page, to make it work. Is there any Trick, how I can make this work?

Here is a very simplified version of my code:

$(document).ready(function(){
  $('#toright').click(alert(">> was clicked"));
});

$(document).ready(function(){
  $('#toleft').click(alert("<< was clicked"));
});

$(document).ready(function(){
  $('#save').click(alert("save was clicked"));
});

$(document).ready(function() {
    alert("The document is ready!");
});

After the site is rendered, it does not show my function, but when I type the URL into my address-bar, it works.


Some EDITS:

  • I'm using Rails 4.0.1
  • I have the js.erb in my assets folder
  • Ok. I've put them all in one $(document).ready, but I still have to reload my file for making my JS work.

UPDATE:

So I have edited my application.js to contain

$(document).ready(function(){
alert("The document is ready!");    
$('#toright').click(alert(">> was clicked"));
$('#toleft').click(alert("<< was clicked"));
$('#save').click(alert("save was clicked"));
});

and put my js.erb to be only .js in my assets/javascripts folder. But anyway, it just won't work until I have refreshed the page.



Solution 1:[1]

ready is a jQuery function, thus ensure you to use and include properly the jQuery library in your Javascript.

Furthermore, if you don't need to exchange data between your controller and your Javascript, I advice you to put your Javascript in your asset folder, for instance: /app/assets/application.js.

This is possible only for the Rails applications 3.x and 4.x.

Best regards.

Solution 2:[2]

Since the introduction of turbolinks in rails 4 you can use:

$(document).on('turbolinks:load', function() {
  // Events
}

Instead of:

$(document).ready(function(){
  // Events
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Geoffrey
Solution 2 Lukas -.-