For example i have many comments rendered for the post.
<%= render post.comments %>
And in comments partial i have javascript wich will repeated so many times how many comments i have
_comment.html.erb
<div id="content_<%= comment.id %>"><%= comment.content %></div>
<script>$("content_<%= comment.id %>").click(function() { alert('content of comment <%= comment.id %>') });</script>
What is the best way to avoid repeating javascript in source code?
I tried to create *_comment.js.erb* file and put javascript there, but i don’t understand how to make it work.
Can anyone please explain me how to solve this problem?
You can change the implementation to have a single js file under app/assets/javascripts with your script inside. change the selector of the script to match the class of the comments instead of a unique ID. If required, use javascript to read the content of elements, instead of doing this on the server as you do now.