Skip to content

Instantly share code, notes, and snippets.

@Kuzcoo
Created March 3, 2016 20:34
Show Gist options
  • Save Kuzcoo/164b51e9a63f3e4b723e to your computer and use it in GitHub Desktop.
Save Kuzcoo/164b51e9a63f3e4b723e to your computer and use it in GitHub Desktop.
Full width iframes (for example, videos)
(function () {
let ratios = [];
let resizeIframes = function (iframes, ratio) {
let winW = window.innerWidth;
iframes.forEach( (iframe,i) => {
let [w, h] = [iframe.clientWidth, iframe.clientHeight],
_ratio = ratio && ratio[i] || h/w;
// set iframe size
iframe.style.height = winW*_ratio+'px';
iframe.style.width = '100%';
// if first call, store original iframe ratio
if (ratios.length !== iframes.length) { ratios.push(_ratio);}
});
};
// poll until iframes are inserted in the dom
let pollIframe = function () {
let iframes = document.querySelectorAll('iframe');
if (iframes.length === 0) {
return setTimeout(pollIframe, 100);
}
let iframesList = [].slice.call(iframes);
resizeIframes(iframesList);
// listen to resize event
window.addEventListener('resize', function () {
resizeIframes(iframesList, ratios);
});
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment