I'm looping a set of div's conaining an id for YouTube videos to get and show their titles, descriptions, etc. The divs I loop through look like this:
<div class="tutorialVideoDataContainer" data-clipid="xxxxxxxxxxx"></div>
<div class="tutorialVideoDataContainer" data-clipid="xxxxxxxxxxx"></div>
<div class="tutorialVideoDataContainer" data-clipid="xxxxxxxxxxx"></div>
<div class="tutorialVideoDataContainer" data-clipid="xxxxxxxxxxx"></div>
<div class="tutorialVideoDataContainer" data-clipid="xxxxxxxxxxx"></div>
For some reason the loop adds all of the info to the last of these divs instead of applying the info to the current div inside the loop. Any idea why this is?
And also, as a sub question, why can't I reach i inside the ajax call? I have to set tutorial = tutorials[i] and append the children to tutorial instead of tutorials[i] but I can't use just tutorials[i] within the ajax part. I can't understand what the difference is.
(function () {
var tutorials = document.getElementsByClassName('tutorialVideoDataContainer');
for (var i = 0; i < tutorials.length; i++) {
var tutorial = tutorials[i];
console.log(i);
console.log(tutorial);
console.log(tutorials[i]);
var id = tutorial.getAttribute('data-clipid');
$.ajax({
url: "http://gdata.youtube.com/feeds/api/videos/" + id + "?v=2&alt=json",
dataType: "jsonp",
success: function (data) {
var title = data.entry.title.$t;
var description = data.entry.media$group.media$description.$t;
var duration = data.entry.media$group.media$content[0].duration;
var thumbnail = data.entry.media$group.media$thumbnail[3].url;
if (title.length > 0) {
var titleElement = document.createElement("h3");
titleElement.innerText = title;
tutorial.appendChild(titleElement);
}
if (description.length > 0) {
var descriptionElement = document.createElement("p");
descriptionElement.innerText = description;
tutorial.appendChild(descriptionElement);
}
var minutes = Math.floor(duration / 60);
var seconds = duration - minutes * 60;
var durationElement = document.createElement("p");
durationElement.innerText = minutes + ":" + seconds;
tutorial.appendChild(durationElement);
var clickLink = document.createElement("a");
clickLink.className = "showOverlayVideo";
var thumbnailElement = document.createElement("img");
thumbnailElement.src = thumbnail;
thumbnailElement.alt = title;
clickLink.appendChild(thumbnailElement);
tutorial.appendChild(clickLink);
}
});
}
})();