8

I have a ruby loop that creates a list of comments..

I wonder if I can attach jQuery function to Rails link_to helper in this case?

    <% @video.phrases.each do |phrase| %> 
    <div class = "span4" id ="comment" ><%= phrase.content %></div><a id ="ff"  ><%= image_tag("ff.png", :size=> "32x32" )%></a>
    <% end %>

I am hoping for something like

    <% @video.phrases.each do |phrase| %> 
    <div class = "span4" id ="comment" ><%= phrase.content %></div><%= link_to (image_tag("ff.png", :size=> "32x32" ), html => {<script>$("#video_div").html('CONTENTS OF HTML');</script>} :remote => true %>
    <% end %>

I know it won't work, but I wonder is there an easy way to achieve this kind of functionality?

Thanks!

Stpn
  • 6,202
  • 7
  • 47
  • 94

3 Answers3

7

You can do this two ways.

The first is the add an html attribute on the link_to:

<% @video.phrases.each do |phrase| %> 
  <div class = "span4" id ="comment" >
    <%= phrase.content %>
  </div>
  <%= link_to (image_tag("ff.png", :size=> "32x32" ), html => {:onclick => "$('#video_div').html('CONTENTS OF HTML');"} :remote => true %>
<% end %>

The second is to separate the Javascript from Ruby:

<% @video.phrases.each do |phrase| %> 
  <div class = "span4" id ="comment" >
    <%= phrase.content %>
  </div>
  <%= link_to (image_tag("ff.png", :size=> "32x32" ) :remote => true %>
<% end %>

<script type="text/javascript">
  $('a').click(function(){
    $("#video_div").html('CONTENTS OF HTML');
  );
</script>

If you want the contents of the link tag, substitute 'CONTENTS OF HTML' for $(this).html()

grant
  • 142
  • 4
3

Also I actually found out about Rails link_to_function helper and was able to achieve the desired behavior with:

<% @video.phrases.each do |phrase| %> 
 <div class = "span4" id ="comment" ><%= phrase.content %></div><a id ="ff">
  <%= link_to_function image_tag("ff.png", :size=> "32x32" ), "use_comment('#{phrase.comment}')"%>
 </a>
Stpn
  • 6,202
  • 7
  • 47
  • 94
2

You might want to use event delegation, since it seems like you'll be creating a large number of comments.

So, borrowing from grant something like:

<% @video.phrases.each do |phrase| %> 
  <div class = "span4" id ="comment" >
    <%= phrase.content %>
  </div>
  <%= link_to (image_tag("ff.png", :size=> "32x32" ) :remote => true %>
<% end %>
<script type="text/javascript">
  $("#comment-wrapper-name-here").on("click", "a", function() {
    $("#video_div").html('CONTENTS OF HTML');
  );
</script>
Code Maverick
  • 20,171
  • 12
  • 62
  • 114
Neil
  • 51
  • 1