I'm writing an app with Ruby on Rails, jQuery and the Embedly API. I write a video partial like so:
<%= div_for video do %>
<%= link_to 'video', video.video_url, :class => 'oembed' %>
<% end %>
And render that partial in the index
view:
<div id ='video_div'>
<%= render @videos %>
</div>
Then my application.js file takes the link and uses the Embedly API to embed the video and display the thumbnail. I initially hide the video with CSS, and I want the each video with its respective thumbnail to be in its own div. This means that I want every video/thumbnail pair to be in its own div, so that I can position the thumbnail directly on top of the video. I tried doing this:
$('a.oembed').embedly({maxWidth:300,'method':'replace'}).bind('embedly-oembed', function(e, oembed){
var id = $(this).parent().attr('id');
$(id).append($("<img>", { src: oembed.thumbnail_url, width:200 }));
});
My thinking is that since the div_for embedded ruby creates a div with a unique id surrounding each video that was originally a link, I would go to the parent of the link (the div with the unique id), and get the unique id attribute, and then append the thumbnail to that div. However, after checking my HTML code in the browser, the thumbnail is not getting appended. What am I doing wrong, and how can I get what I want?
It looks like the problem is this line:
$(id).append($("<img>", { src: oembed.thumbnail_url, width:200 }));
It should be:
$('#' + id).append($("<img>", { src: oembed.thumbnail_url, width:200 }));
However, $(this).parent()
is already returning the element you are after, so all the work you are doing with its id is not needed:
$(this).parent().append("<img>" ...);