I'm trying to grab the title of the youtube video and print it on a page, under the thumbnail of this video.
Everything works fine, I got the API key, and the titles are printing to the console. But It's done with Ajax so I have to make everything wait for the title to come. And that's where I'm stuck.
So how do I make the code/loop wait for Ajax to finish it's doing?
My simplified code. I tried posting it on code pen but no luck with making js work. https://codepen.io/anon/pen/JyYzwM
Link to a live page with it. It works there and you can see the console returns the titles. http://boiling-everglades-49375.herokuapp.com/video.php
$('.category-shape').on('click', function () {
var documentary = ["siAPGGuvPxA", 'i6Hgldw1yS0', 'Omg1gMNtVpY', 'MfWHPnxrDI4', 'aT0HduxW8KY'];
showVideos(documentary);
}
function showVideos(channel) {
if (!isFirstPass) {
$('#addedContent').remove();
}
$('#dropdownVideoPicker').append('<div id="addedContent"></div>');
console.log(" ");
for (var i = 0; i < channel.length; i++) {
var title = getTitle(channel[i]);
$.when(getTitle(channel[i])).done( function () {
var pageCode = generatePageCode(channel[i], title);
console.log(getTitle(channel[i]));
$('#addedContent').append(pageCode);
});
}
$('#addedContent').hide();
$('#addedContent').slideDown();
isFirstPass = false;
$("html, body").animate({scrollTop: ($('.category-shape:nth-of-type(6)').offset().top)}, 1000);
grabYtId();
}
function grabYtId() {
$('.videoThumbnail').on('click', function () {
var $ytId = $(this).attr('src').slice(27, -6);
showModalWindow($ytId);
});
}
function showModalWindow(Id) {
var $theModal = $("#videoModal"),
iframe = $("#iframe")[0],
videoSRC = 'https://www.youtube.com/embed/' + Id,
videoSRCauto = videoSRC + "?autoplay=1&rel=0&controls=1&showinfo=0";
$(iframe).attr('src', videoSRCauto);
$('button.close').click(function () {
$(iframe).attr('src', videoSRC);
});
$theModal.on("hidden.bs.modal", function () {
$(iframe).attr('src', videoSRC);
});
}
And that's the function that grabs the titles
function getTitle(videoId) {
$.ajax({
url: "https://www.googleapis.com/youtube/v3/videos?id=" + videoId + "&key=" + "AIzaSyCDyE576FU2QRbkHivxHfrjbEjPwartzKo" + "&fields=items(snippet(title))&part=snippet",
dataType: "jsonp",
success: function (data) {
var title = data.items[0].snippet.title;
console.debug("function: " + title);
var titleLoaded = new CustomEvent('titleLoaded', {
detail: {
loaded: true
}
});
$('body')[0].dispatchEvent(titleLoaded);
return title;
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus, +' | ' + errorThrown);
}
});
}
And yes, I know that giving an API key to the public is a bad idea but I'll change it add a website restriction in google.