Skip to content

Instantly share code, notes, and snippets.

@aloyr
Created February 12, 2020 00:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aloyr/d897d9734fbab219e9f69e6793bf84dc to your computer and use it in GitHub Desktop.
Save aloyr/d897d9734fbab219e9f69e6793bf84dc to your computer and use it in GitHub Desktop.
// Some structure lifted from the official API docs.
// https://developers.google.com/youtube/iframe_api_reference#Loading_a_Video_Player
// 1. Prep elements.
newPlayer = document.createElement('div');
newPlayer.setAttribute('id', 'yttest');
newPlayer.style.filter = 'grayscale(1) brightness(0.5)';
newPlayer.style.transition = '1s';
document.querySelectorAll('.flex-layout-base')[0].appendChild(newPlayer);
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
var playerState;
var playerStateReverse;
function onYouTubeIframeAPIReady() {
playerState = YT.PlayerState;
playerStateReverse = Object.keys(YT.PlayerState).reduceRight((accum, key, i) => {
accum[playerState[key]] = key;
return accum;
}, {});
player = new YT.Player('yttest', {
height: '720',
width: '1280',
videoId: '2ZwQia4lkpI',
playerVars: {rel: '0', showinfo: '0', modesbranding: '1'},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
console.log('player ready');
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
console.log('state change', playerStateReverse[event.data], event.data);
if (event.data === 1) {
player.a.style.filter = 'grayscale(0) brightness(1)';
console.log('state change', 'remove grayscale');
}
else {
player.a.style.filter = 'grayscale(1) brightness(0.5)';
console.log('state change', 'apply grayscale');
}
}
function stopVideo() {
console.log('stop video');
player.stopVideo();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment