Reputation: 347
I have a page of about 15-20 YouTube videos I’d like to dynamically update the img src to point to the YouTube hosted thumbnails. From a logic perspective, I want to find every DIV with a class of “videos”, get the ID of that class and update the image source with the dynamically inserted value, e.g., http://img.youtube.com/vi/DbyNtAQyGs/0.jpg in the first example. All IDs are unique because they are the YouTube video IDs and there is only one img tag under each “videos” class.
This code would run on page load so it would have to be pretty fast to ensure the values are set before the browser passes the each img tag in the DOM. Hoping I can get one of those one liners instead of vars and multiple lines.
<div id="DbyNtAQyGs" class="videos">
<a href="javascript: void(0);" onclick="loadPlayer($(this).closest('div').attr('id'));)"><img src="" width="212" height="124" /></a>
</div>
<div id="Fh198gysGH" class="videos">
<a href="javascript: void(0);" onclick="loadPlayer($(this).closest('div').attr('id'));)"><img src="" width="212" height="124" /></a>
</div>
Current Code
$('.videos img').attr('src', 'http://img.youtube.com/vi/' + $(this).closest('div').attr('id')); + '/0.jpg');
Upvotes: 0
Views: 307
Reputation: 414
Loop through the .videos elements:
$('.videos').each(function(){
var $this = $(this),
_id = $this.attr('id'); // Capture the ID
// Construct the img src
$this.find('img').attr('src', 'http://img.youtube.com/vi/' + _id + '/0.jpg');
});
Bonus: chain in the click event for your anchor:
$this.find('a').click(function(e){
e.preventDefault();
loadPlayer(_id);
}).find('img').attr('src', 'http://img.youtube.com/vi/' + _id + '/0.jpg');
So you can simplify your markup:
<div id="DbyNtAQyGs" class="videos">
<a href="#"><img src="" width="212" height="124" /></a>
</div>
Upvotes: 0
Reputation: 207861
You can use:
$('.videos img').attr('src', function() { return 'http://img.youtube.com/vi/' + $(this).closest('div').attr('id') + '/0.jpg'; })
Upvotes: 1