Note: In order to make sure your javascript works, add "enablejsapi=1" parameter to the src atttribute. Please check below HTML code.
HTML Code
<h1>In page youtube video player API</h1>
<br/>
<h2><span id="YTvideoLoadTime"></span> </h2>
<h3>Check console logs for player events</h3>
<iframe id='player' width="560" height="315"
src="https://www.youtube.com/embed/axCKOu3YjmM?list=PLkBe8kbE_7-xmNihqYr19TlYGH7jUhQkY&enablejsapi=1" frameborder="5" allowfullscreen></iframe>
//YOUTUBE API
var player;
var timerStart, timetaken;
jQuery(document).ready(function ($) {
console.log("ready!");
loadPlayer();
});
function getArtistId() {
return 'axCKOu3YjmM';
}
function loadPlayer() {
console.log("Youtube IFRAME api");
timerStart = Date.now();
if (typeof (YT) == 'undefined' || typeof (YT.Player) == 'undefined') {
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
window.onYouTubePlayerAPIReady = function () {
// console.log("YT undefined calling onYouTubePlayer ");
onYouTubePlayer();
};
} else {
// console.log("calling onYouTubePlayer ");
onYouTubePlayer();
}
}
function onYouTubePlayer() {
player = new YT.Player('player', {
// height: '490',
//width: '880',
// videoId: getArtistId(),
// playlist: 'PLkBe8kbE_7-xmNihqYr19TlYGH7jUhQkY',
playerVars: {
controls: 1,
showinfo: 0,
rel: 0,
showsearch: 0,
iv_load_policy: 3
},
events: {
'onStateChange': onPlayerStateChange,
'onError': catchError,
'onReady': onPlayerReady
}
});
}
var done = false;
function onPlayerStateChange(event) {
console.log("onPlayerStateChange: " + event.data);
if (event.data == YT.PlayerState.PLAYING ) {
console.log("playing");
done = true;
} else if (event.data == YT.PlayerState.ENDED) {
console.log("ended");
location.reload();
}
else if (event.data == YT.PlayerState.PAUSED) {
console.log("paused");
}
}
function onPlayerReady(event) {
//console.log("onPlayerReady");
timetaken = Date.now() - timerStart;
$('#YTvideoLoadTime').html("Youtube Video player has loaded in : " + timetaken / 1000 + " seconds");
}
function catchError(event) {
if (event.data == 100) console.log("ERROR");
}
function stopVideo() {
console.log("stopVideo");
player.stopVideo();
}
Check Demo
No comments:
Post a Comment
If you have any doubts or questions, please let us know.