Call jQuery function from Rails link_to

Stpn picture Stpn · Apr 13, 2012 · Viewed 11.6k times · Source

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!

Answer

grant picture grant · Apr 13, 2012

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()