0

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.

Saggex
  • 3,390
  • 3
  • 22
  • 37
  • Do you included javascript tag in the view page? – Pavan Apr 09 '14 at 08:23
  • What `Rails` version? use `turbo-links`? – Roman Kiselenko Apr 09 '14 at 08:28
  • Do you realize that you can put all four lines of code in one `$(document).ready()` callback? You don't need four of them. – jfriend00 Apr 09 '14 at 08:28
  • `document.ready()` works just fine with rails. If you are loading content dynamically (e.g. with an ajax call), then that content may be loaded AFTER `document.ready()` fires and thus the code will run before the content is available. You will need to make sure any code that installs event handlers is run AFTER any dynamic content is loaded or you use [delegated event handling](http://stackoverflow.com/questions/8752321/jquery-live-vs-on-method-for-adding-a-click-event-after-loading-dynamic-ht/8752376#8752376). – jfriend00 Apr 09 '14 at 10:28
  • The answer here may help: http://stackoverflow.com/questions/18770517/rails-4-how-to-use-document-ready-with-turbo-links –  Feb 16 '15 at 19:59

2 Answers2

0

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.

Geoffrey
  • 193
  • 3
  • 11
0

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

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

Instead of:

$(document).ready(function(){
  // Events
}
Lukas -.-
  • 367
  • 3
  • 12