Skip to content

Instantly share code, notes, and snippets.

@Punk-UnDeaD
Last active December 9, 2019 15:20
Show Gist options
  • Save Punk-UnDeaD/3a3828ca8954684327fba454b853e786 to your computer and use it in GitHub Desktop.
Save Punk-UnDeaD/3a3828ca8954684327fba454b853e786 to your computer and use it in GitHub Desktop.
youtube api
window.Drupal = window.Drupal || {};
((document) => {
let tag = document.querySelector('script[src*="youtube.com/iframe_api"]');
const html = document.querySelector('html');
let timer;
let YT = null;
Drupal.YT = function (callback) {
if (YT) {
callback(YT);
return;
}
html.addEventListener('YouTubeIframeAPIReady', e => callback(YT));
if (!tag) {
tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
document.querySelector('head').append(tag);
}
if (!timer) {
timer = setInterval(() => {
if (window.YT && window.YT.Player) {
clearInterval(timer);
YT = window.YT;
html.dispatchEvent(new CustomEvent('YouTubeIframeAPIReady'));
}
}, 33);
}
};
})(document);
Drupal.behaviors['youtube-bg-video'] = {
attach: function (context, settings) {
context.querySelectorAll('div.youtube-bg-video').forEach(div => {
const wrapper = div.closest('.iframe-wrapper');
fetch(`https://api.allorigins.win/get?url=https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=${div.dataset.id}&format=json`)
.then(response => response.json())
.then(response => JSON.parse(response.contents))
.then(e => wrapper && wrapper.style.setProperty('--ratio', e.height / e.width * 100 + '%'));
Drupal.YT((YT) => {
new YT.Player(div, {
videoId: div.dataset.id,
playerVars: {
autoplay: 1,
controls: 0,
loop: 1,
rel: 0,
playlist: div.dataset.id,
showinfo: 0,
mute: 1
}
});
})
})
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment