I’m trying to loop over every YouTube video in a page (using the iframe embed method) and append to each the title of the video, using jQuery. My HTML looks something like this:
<div class="video-wrapper">
<div class="video-container">
<iframe src="http://www.youtube.com/embed/qzNSsDD_LzE" frameborder="0" allowfullscreen></iframe>
</div>
</div>
<div class="video-wrapper">
<div class="video-container">
<iframe src="http://www.youtube.com/embed/9bZkp7q19f0" frameborder="0" allowfullscreen></iframe>
</div>
</div>
And the jQuery looks like this:
var video = $('.video-container');
video.each(function() {
var youTuberegex = /(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=))([\w-]{10,12})/g,
videoID = youTuberegex.exec($(this).find('iframe').attr('src'))[1];
$.getJSON('http://gdata.youtube.com/feeds/api/videos/'+videoID+'?v=2&alt=jsonc', function(data){
var videoTitle = data.data.title;
video.after('<figcaption>'+videoTitle+'</figcaption>');
});
});
So, I am (trying to) take each video and use a regex to extract the ID. I then use the video feed to retrieve the title, and append it to the video-container.
This is in a jsFiddle. As you can see, the problem is that the title of each video is appended every time. Where am I going wrong, and is this an efficient way to achieve what I am after?
The video variable refers to the entire set of objects that match the selector “.video-container” so when you are doing
It is doing that on each one.
What you need to do is something like:
The videoBox variable points to the specifc div for that video.