Skip to content

Instantly share code, notes, and snippets.

@timbielawski
Last active December 31, 2018 07:55
Show Gist options
  • Save timbielawski/f7c0640f766be421eb11b0ecb7e280cc to your computer and use it in GitHub Desktop.
Save timbielawski/f7c0640f766be421eb11b0ecb7e280cc to your computer and use it in GitHub Desktop.
Javascript function to find youtube embeds / iframes in an element and make them responsive
adjustYoutubeEmbed = element => {
if (element) {
const iframes = element.getElementsByTagName("iframe");
for (let i in iframes) {
if (iframes[i].src && iframes[i].src.match(/^https:\/\/www\.youtube\.com/)) {
let iframe = iframes[i];
iframe.setAttribute("style", "position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: 0;");
const width = iframe.width;
const height = iframe.height;
let paddingTop = 0;
if(width > 0){
paddingTop = height/width * 100;
}
const parent = iframe.parentNode;
const wrapper = document.createElement("div");
wrapper.setAttribute("style", `position: relative; overflow: hidden; padding-top: ${paddingTop}%`);
parent.replaceChild(wrapper, iframe);
wrapper.appendChild(iframe);
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment