Saturday, June 1, 2024
101
rated 0 times [  103] [ 2]  / answers: 1 / hits: 86594  / 14 Years ago, mon, august 9, 2010, 12:00:00

Rails 3 has some unobtrusive JavaScript which is pretty cool.



But I was wondering what the best way is to include additional JavaScript for a particular page.



For example, where I might have previously done:



<%= f.radio_button :rating, 'positive', :onclick => $('some_div').show(); %>


We can now make it unobtrusive with something like



<%= f.radio_button :rating, 'positive' %>

# then in some other file
$('user_rating_positive').click(function() {
$('some_div').show();
}


So I guess my question is where/how to include that JavaScript? I don’t want to fill up the application.js file because this JavaScript is only applicable to this one view. Should I include a custom JavaScript file for each page somehow, or stick it in an instance variable that the header looks for?


More From » ruby-on-rails

 Answers
3

What I like to do is include the per-view Javascript in a content_for :head block and then yield to that block in your application layout. For example



If it's pretty short then:



<% content_for :head do %>
<script type=text/javascript>
$(function() {
$('user_rating_positve').click(function() {
$('some_div').show();
}
});
</script>
<% end %>


or, if longer, then:



<% content_for :head do %>
<script type=text/javascript>
<%= render :partial => my_view_javascript
</script>
<% end %>


Then, in your layout file



<head>
...
<%= yield :head %>
</head>

[#95987] Thursday, August 5, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cruzs

Total Points: 710
Total Questions: 113
Total Answers: 100

Location: Nepal
Member since Sat, Jul 18, 2020
4 Years ago
cruzs questions
Thu, Nov 26, 20, 00:00, 4 Years ago
Wed, Oct 28, 20, 00:00, 4 Years ago
Wed, Aug 19, 20, 00:00, 4 Years ago
Sun, Aug 2, 20, 00:00, 4 Years ago
;