The solution is a little bit more complicated than you could imagine but it's possible.
First, you need to load some more resources in your page :
Then, you need to wrap your whole fancybox initialization code (including the .ready()
method) inside the onYouTubePlayerAPIReady()
function like :
function onYouTubePlayerAPIReady() {
$(document).ready(function () {
$.fancybox.open([...],{
// API options
}); // fancybox
}); // ready
};
The function above will allow you to detect events from the youtube player (e.g. start, pause, end of video, etc.)
Additionally, you have to create another function to handle the youtube events (it will be called from within fancybox callbacks)
function onPlayerStateChange(event) {
// callback for youtube events
};
Now, the fun is in detecting both fancybox and youtube events :
- is the content video or image? if video: pause the slideshow.
- what is the fancybox slideshow status: pause or active?
- is the youtube video finished? so we can resume the slideshow
- what if the visitor advances the gallery manually while watching the video? the end of the video is not detected and the slideshow may not resume
Follow is the full documented code (without the gallery elements to make it shorter).
See it working JSFIDDLE
function onPlayerStateChange(event) {
if (event.data === 0) {
// video is finished
$.fancybox.play(); // resume slide show
}
}
function onYouTubePlayerAPIReady() {
$(document).ready(function () {
$.fancybox.open([....], {
autoPlay: true,
playSpeed: 3000,
helpers: {
media: {}
},
beforeLoad: function () {
// the coming content is iframe (video)
// and the slideshow is active/running
if (this.type == "iframe" && $.fancybox.player.isActive) {
$.fancybox.play(); // pause slide show
} else if (!$.fancybox.player.isActive) {
// the slideshow is paused
// most likely we advanced gallery using arrows
$.fancybox.play(); // resume slideshow
};
},
beforeShow: function () {
if (this.type == "iframe") {
// bind callback to youtube events
var id = $.fancybox.inner.find('iframe').attr('id');
var player = new YT.Player(id, {
events: {
onStateChange: onPlayerStateChange
}
});
};
},
margin: [20, 60, 20, 60] // Increase left/right margin
}); // fancybox
}); // ready
} // youtube API ready
You will notice some CSS code in the JSFIDDLE that makes the fancybox navigation arrows to move outside fancybox while playing the video only (also notice the API option margin
.) This allows you to have access to youtube's controls, which would be blocked by the arrows otherwise.
LAST NOTE :
This solution works with youtube videos only. For other type of videos, you may need to implement their own API to handle video change events.