I am trying to extract the video ID that is contained within the URL of a YouTube video and then store that ID in a variable that I can reference in creating an iframe to embed the YouTube video.
Below is my code:
$(".result").live("click", function () {
var result_number = 0;
youtubequery = "https://gdata.youtube.com/feeds/api/videos?category=Music&q=thesongstitle&v=2&alt=json&max-results=5";
youtubeid = "";
$.getJSON(youtubequery, function (vid_data) {
$.each(vid_data.feed.entry, function (e, vid) {
if (e == result_number) {
youtubeid = vid.id.$t.substring(27);
}
});
});
iframehtml = "<iframe height='300' width='400' src='http://www.youtube.com/embed/" + youtubeid + "?autoplay=1' frameborder='0' allowfullscreen></iframe>";
$("#youtube_vid").html(iframehtml);
});
When I click on a div of the class “result” the first time the YouTube ID is not included in the iframe html stored in the variable iframehtml. But, when I click it the second time, everything works as expected.
Does anyone know what could be causing this?
I was able to get it to work when I included the creation of the iframehtml variable and the line that puts the html in #youtube_vid, but due to the functionality of my site I cannot code it that way.
your getJSON function is performing a asynchronous http get request. So when you call it, it returns before the data comes back from the request. By the time you click .result again the data has returned. try putting
inside your getJSON callback function, there will be a delay before the html shows, but it will work.