Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
193
rated 0 times [  200] [ 7]  / answers: 1 / hits: 34774  / 11 Years ago, thu, july 11, 2013, 12:00:00

I'm having some trouble loading my javascript when I use a link_to helper in rails. When I either manually enter the url with 'localhost:3000/products/new' or reload the page, the javascript loads, but when I go through a link as written below, the jQuery $(document).ready will not load on the new page.



Link_to, javascript does not load when I click this link:



<%= link_to New Product, new_product_path %>


products.js file



$(document).ready(function() {
alert(test);
});


Any help would be much appreciated. Thanks in advance!


More From » jquery

 Answers
6

Are you using Rails 4? (Find out by doing rails -v in your console)



This issue is probably due to the newly added Turbolinks gem. It makes your application behave like a single page JavaScript application. It has a few benefits (it's faster), but it unfortunately breaks some existing events like $(document).ready() because the page is never reloaded. That would explain why the JavaScript works when you directly load the URL, but not when you navigate to it through a link_to.



Here's a RailsCast about Turbolinks.



There are a couple solutions. You can use jquery.turbolinks as a drop-in fix, or you can switch your $(document).ready() statement to instead use the Turbolinks 'page:change' event:



$(document).on('page:change', function() {
// your stuff here
});


Alternatively, you could do something like this for compatibility with regular page loads as well as Turbolinks:



var ready = function() {
// do stuff here.
};

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


If you are using Ruby on Rails >5 (you can check by running rails -v in the console) use 'turbolinks:load' instead of 'page:change'



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

[#77055] Wednesday, July 10, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lindsay

Total Points: 402
Total Questions: 109
Total Answers: 109

Location: Tuvalu
Member since Sat, Feb 11, 2023
1 Year ago
;