Friday, 9 December 2016

Quick XPages Tip: Responsive Videos using the YouTube IFrame Player API and CSS in XPages


This past week I was asked to embed a video on a XPages in which the sound had to be muted when the XPages was opened and the video played automatically. Given the default option 'volume = 0' no longer works in case an iframe is used (see example below), I decided to use the YouTube IFrame Player API including a CSS file in this specific case. Below an example of the use of the YouTube IFrame Player API in a XPage.

<div class="video-container">
<iframe id="video" width="560" height="315" src="https://www.youtube.com/embed/PYpD7H3lNGA?autoplay=1;controls=0;loop=1;showinfo=0;volume=0;playlist=PYpD7H3lNGA"
frameborder="0" allowfullscreen="">
</iframe>
</div>

Basic setup YouTube IFrame Player API with some additional options
<script src="https://www.youtube.com/iframe_api"></script>
<script>
function onYouTubeIframeAPIReady() {
var player;
player = new YT.Player('video1', {
videoId: 'PYpD7H3lNGA', // YouTube Video ID
playerVars: {
autoplay: 1,  // Auto-play the video on load
controls: 0,  // Show pause/play buttons in player
showinfo: 0,  // Hide the video title
modestbranding: 0,  // Hide the Youtube Logo
loop: 1,   // Run the video in a loop
fs: 0,  // Hide the full screen button
cc_load_policy: 0,  // Hide closed captions
iv_load_policy: 3,  // Hide the Video Annotations
autohide: 0,   // Hide video controls when playing
playlist: 'PYpD7H3lNGA'
},
events: {
onReady: function(e) {
e.target.mute();
}
}
});
}
</script>

Example YouTube IFrame Player API in an XPage
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core"
xmlns:xc="http://www.ibm.com/xsp/custom">
<xp:this.resources>
<xp:styleSheet href="/print.css" media="print"></xp:styleSheet>
<xp:styleSheet href="/video.css"></xp:styleSheet>
</xp:this.resources>
<xc:ccLayout><xp:this.facets>
<xp:panel xp:key="facetMiddle">
<div id="video-container">
<div id="video1"></div>
</div>
<script src="https://www.youtube.com/iframe_api"></script>
<script>
function onYouTubeIframeAPIReady() {
var player;
player = new YT.Player('video1', {
videoId: 'PYpD7H3lNGA', // YouTube Video ID
playerVars: {
autoplay: 1,
controls: 0,
showinfo: 0,
modestbranding: 0,
loop: 1,
fs: 0,
cc_load_policy: 0,
iv_load_policy: 3,
autohide: 0,
playlist: 'PYpD7H3lNGA'
},
events: {
onReady: function(e) {
e.target.mute();
}
}
});
}
</script>
</xp:panel>
</xp:this.facets>
</xc:ccLayout>
</xp:view>

Corresponding CSS file for responsiveness
.video-container {
 position:relative;
 padding-bottom:56.25%; /* 16:9 */
 padding-top:30px;
 height:0;
 overflow:hidden;
}

.video-container iframe, .video-container object, .video-container embed {
 position:absolute;
 top:0;
 left:0;
 width:100% !important;
 height:100% !important;
}

Final result is a responsive video using the YouTube IFrame API Player.
More information YouTube IFrame API Player.

No comments:

Post a Comment