I already know how to play/pause a YouTube video dynamically as you can see from my weave.
However I'm having difficulty getting it to work dynamically with FancyBox using onBlur (when the window is not focused video should pause).
Here's my Pen: http://codepen.io/anon/pen/wJXoJy?editors=0010
// Show Lightbox Video Onload
$.fancybox.open({
youtube : {
controls : 0,
showinfo : 0
},
src : '//www.youtube.com/embed/-AszZcClVXA?enablejsapi=1', // Source of the content
type : 'iframe', // Content type: image|inline|ajax|iframe|html (optional)
});
// Inject YouTube API script
var tag = document.createElement('script');
tag.src = "//www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubePlayerAPIReady(e) {
// create the global player from the specific iframe (#video)
player = new YT.Player($(".fancybox-iframe").attr("id"), {
events: {
// call this function when player is ready to use
'onReady': onPlayerReady
}
});
}
function onPlayerReady() {
window.addEventListener("blur", function() {
player.pauseVideo();
});
}
<link rel="stylesheet" href="//www.fancyapps.com/fancybox/3/fancybox/jquery.fancybox.min.css?v=1490320405" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//www.fancyapps.com/fancybox/3/fancybox/jquery.fancybox.min.js?v=1490320405"></script>
Here is a demo - http://codepen.io/fancyapps/pen/jBKowp?editors=1010
Basically, idea is that you initialize fancyBox after YouTube API is available and then you can use YouTube API methods inside fancyBox callback.
// 1. 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);
// 2. This function initializes fancyBox
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
$('[data-fancybox="group"]').fancybox({
onComplete : function( instance, current ) {
if ( current.type === 'iframe' ) {
var id = current.$content.find('iframe').attr('id');
player = new YT.Player( id, {
events : {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
}
});
}
// 3. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 4. Fires when the player's state changes.
function onPlayerStateChange(event) {
// Go to the next video after the current one is finished playing
if (event.data === 0) {
$.fancybox.getInstance('next');
}
}
// Page Visibility API to pause video when window is not active
$(document).on("visibilitychange", function() {
if ( player ) {
if ( document.hidden ) {
player.pauseVideo();
} else {
player.playVideo();
}
}
});