Skip to content

Instantly share code, notes, and snippets.

@Zemnmez
Last active August 29, 2015 14:13
Show Gist options
  • Save Zemnmez/e245a601cb1857870f75 to your computer and use it in GitHub Desktop.
Save Zemnmez/e245a601cb1857870f75 to your computer and use it in GitHub Desktop.
function dynamicLoadYT(el) {
var videoIDParts = /youtu\.be\/(.*)/;
// invalid link
if (!videoIDParts) return;
var videoID = videoIDParts[1];
//generate a callback function
// (most people would do this with jQuery)
// we add a random long number to prevent
// us overwriting another callback
var callbackName = "callback_" +
Math.random().toString().slice(2);
window[callbackName] = function(data){
var videoEl = document.createElement("div");
videoEl.setAttribute("class", "video")
var title = document.createElement("div");
title.setAttribute("class", "title");
//add the video title
title.appendChild(document.createTextNode(data.data.title));
videoEl.appendChild(title);
//add an embedded video
videoEl.appendChild(document.createElement("iframe")).src =
"http://www.youtube.com/embed/" + data.data.id + "?autoplay=1";
//replace the anchor with the div containing the video
el.parentNode.replaceChild(
videoEl,
el
);
}
//make a call to the JSONP API.
document.body.appendChild(document.createElement("script")).src =
"https://gdata.youtube.com/feeds/api/videos/" + videoID + "?v=2&callback=" + callbackName;
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment