Skip to content

Instantly share code, notes, and snippets.

@roberrrt-s
Created March 5, 2021 11:15
Show Gist options
  • Save roberrrt-s/e477e1b1e35e358e2371bd744dc48ccc to your computer and use it in GitHub Desktop.
Save roberrrt-s/e477e1b1e35e358e2371bd744dc48ccc to your computer and use it in GitHub Desktop.
/* global YT */
import YouTube from '../util/YouTube';
export default (function() {
function init() {
let isPlaying = false;
let hasStarted = false;
const _$videoWrapper = $('.js-hero-video');
const videoId = _$videoWrapper.data('video-id');
videoId ? YouTube.init(videoId, 'js-hero-player', ready, state) : null;
// Callback function for onStateChange (per YouTube API)
function state(e, player) {
switch(e.data) {
// Fires as soon as the YouTube video inits, alternative to onReady
case YT.PlayerState.UNSTARTED:
if(!hasStarted) {
player.mute();
player.playVideo();
hasStarted = true;
}
else {
// On mobile devices, playing is prohobited unless the user clicks somewhere first. By listening to a body click, we can start the playing on mobile
$('body').on('click touchstart', () => {
if(!isPlaying) {
player.mute();
player.playVideo();
isPlaying = true;
}
})
}
break;
case YT.PlayerState.ENDED:
// Forces video to replay and skip recommended videos.
player.playVideo();
break;
case YT.PlayerState.PLAYING:
// When the video first plays, the logo etc is all visible, we wait three seconds for the watermark to dissapear, then reset the time and fade in the video.
if(!isPlaying) {
setTimeout(function() {
player.seekTo(0);
_$videoWrapper.addClass('has-active-video');
}, 3000)
}
isPlaying = true;
break;
case YT.PlayerState.PAUSED:
break;
case YT.PlayerState.BUFFERING:
break;
default:
console.log('Error, unspecified YouTube PlayerState');
}
}
// Default callback for onReady (Per YouTube API)
function ready(e, player) {
player.mute();
player.playVideo();
// Enables resize function for the video
$(window).on('resize', onResize);
onResize();
}
function onResize() {
// Get the current document width and height
let width = $(window).width();
let height = $(window).height();
let video = _$videoWrapper.find('iframe');
// Decide whether we use the width or height as input, depending on their values after the initial aspect ratio calculations
if(width / 16 > height / 9) {
// Width is longer, so calculate height based on width
video.width(width);
video.height(width * 0.5625)
}
else {
// Height is longer, so calculate width based on height
video.width(height * 1.77777778);
video.height(height)
}
}
}
return {
init,
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment