I'm trying to put this code in an module function:
$(document).ready(function()
{
VIDEO.onYouTubeIframeAPIReady();
}
var VIDEO = (function (my, $){
var tag = document.createElement('script');
var onPlayerStateChange;
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
my.onYouTubeIframeAPIReady =function() {
player = new YT.Player('player', {
height: '490',
width: '880',
videoId: SONG.getArtistId(),
playerVars: { controls:1, showinfo: 0, rel: 0, showsearch: 0, iv_load_policy: 3 },
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange,
'onError': catchError
}
});
}
function onPlayerReady(event) {
if(typeof(SONG.getArtistId()) == undefined)
{
console.log("undefineeeed");
}
event.target.playVideo();
}
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
// setTimeout(stopVideo, 6000);
done = true;
}
if(event.data == YT.PlayerState.ENDED)
{
location.reload();
}
}
function catchError(event)
{
if(event.data == 100) console.log("De video bestaat niet meer");
}
function stopVideo() {
player.stopVideo();
}
return my;
}(VIDEO || {}, jQuery));
The problem is: even it's self-executing, nothing happens and the iFrame is not shown.
I'm trying to do this because it's part of an assignment. We have to work in modules.
You need to simplify the code :
HTML
<div id="player"></div>
Javascript
$(document).ready( function() {
console.log( "ready!" );
loadPlayer();
});
function getArtistId() {
return 'l-gQLqv9f4o';
}
function loadPlayer() {
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() {
onYouTubePlayer();
};
} else {
onYouTubePlayer();
}
}
var player;
function onYouTubePlayer() {
player = new YT.Player('player', {
height: '490',
width: '880',
videoId: getArtistId(),
playerVars: { controls:1, showinfo: 0, rel: 0, showsearch: 0, iv_load_policy: 3 },
events: {
'onStateChange': onPlayerStateChange,
'onError': catchError
}
});
}
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
// setTimeout(stopVideo, 6000);
done = true;
} else if (event.data == YT.PlayerState.ENDED) {
location.reload();
}
}
function onPlayerReady(event) {
//if(typeof(SONG.getArtistId()) == undefined)
//{
// console.log("undefineeeed");
//}
//event.target.playVideo();
}
function catchError(event)
{
if(event.data == 100) console.log("De video bestaat niet meer");
}
function stopVideo() {
player.stopVideo();
}
And a live example : http://jsbin.com/maweqahuhi/1/ http://jsbin.com/nipogicide/2/
EDIT
Regarding your commentq i made some changement in the code.
You need to use onYouTubePlayerAPIReady() to call the player later. I edited all the previous code.
Related
I want to have a play / pause toggle button that controls my youtube video.
<a id="play-button">Play / Pause</a>
Right now it is just a link. This is the javascript code for the onPlayerReady function
function onPlayerReady(event) {
var playButton = document.getElementById("play-button");
playButton.addEventListener("click", function(event) {
if (event.data==YT.PlayerState.PLAYING) {
player.pauseVideo();
}else {
player.playVideo();
}
});
For some reason when I click the link it always does the else command. How can I get it to recognize that the video is currently playing? Is there a better way to do this play / pause toggle action?
SOLUTION for onPlayerStateChange
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.BUFFERING) {
event.target.setPlaybackQuality('hd1080');
}
if (event.data == YT.PlayerState.PAUSED) {
$("#play-button").attr("src", "http://www.beached.tv/assets/play-0a292db2c7cb500e5e768d0222ef1f94.svg");
this.is_playing = false;
}
if (event.data == YT.PlayerState.PLAYING) {
$("#play-button").attr("src", "http://www.beached.tv/assets/pause-c1c0a3d060f908372ebecf2eb7e7c018.svg");
this.is_playing = true;
}
}
FULL CODE
<div id="centerplayer">
<div id="player"></div>
<script>
var is_playing = false;
var fullscreen = false;
var live = true;
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '600',
width: '1067',
playerVars:{
autoplay: 1,
controls: 0,
rel: 0,
iv_load_policy: 3,
showinfo: 0
},
loadPlaylist:{
listType:'playlist'
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange,
'onError': onErrorDetect
}
});
}
function onErrorDetect(event){
if (event.data == 100) {
//video request was not found, error occurs when video has been removed or has been marked as private
event.target.nextVideo();
} else{
location.reload();
}
}
function onPlayerReady(event) {
event.target.setPlaybackQuality('default');
event.target.loadPlaylist(gon.playlist,gon.s_index,gon.s_time);
event.target.setLoop(true);
//PLAYER CONTROLS
var playButton = document.getElementById("play-button");
var that = this;
playButton.addEventListener("click", function(click_event) {
if (that.is_playing) {
$("#play-button").attr("src", "http://www.beached.tv/assets/pause-c1c0a3d060f908372ebecf2eb7e7c018.svg");
// if(live){
// var liveimg = document.getElementById('live-icon');
// liveimg.parentNode.removeChild(liveimg);
// live = false;
// }
player.pauseVideo();
}else {
$("#play-button").attr("src", "http://www.beached.tv/assets/play-0a292db2c7cb500e5e768d0222ef1f94.svg");
player.playVideo();
}
});
var muteButton = document.getElementById("mute-button");
muteButton.addEventListener("click", function() {
if(player.isMuted()){
$("#mute-button").attr("src", "http://www.beached.tv/assets/sound-2850c52028b16dd2c2e264c5dddb39ba.svg");
player.unMute();
}else{
$("#mute-button").attr("src", "http://www.beached.tv/assets/mute-8d50674fdbcdd2cc9597f009be41cea9.svg");
player.mute();
}
});
var enlargeButton = document.getElementById("enlarge-button");
enlargeButton.addEventListener("click", function() {
if (fullscreen){
$("#enlarge-button").attr("src", "http://www.beached.tv/assets/resize-enlarge-a44a4204dca596b45aacb25610ee3189.svg");
player.setSize(1067,600);
fullscreen = false;
}else{
$("#enlarge-button").attr("src", "http://www.beached.tv/assets/resize-shrink-f63cf0e6ab1eb2bb8f7223798c4fc9c5.svg");
player.setSize(1410,793);
fullscreen = true;
}
});
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.BUFFERING) {
event.target.setPlaybackQuality('hd1080');
}
if (event.data == YT.PlayerState.PAUSED) {
$("#play-button").attr("src", "http://www.beached.tv/assets/play-0a292db2c7cb500e5e768d0222ef1f94.svg");
this.is_playing = false;
if(live){
var liveimg = document.getElementById('live-icon');
liveimg.parentNode.removeChild(liveimg);
live = false;
}
}
if (event.data == YT.PlayerState.PLAYING) {
$("#play-button").attr("src", "http://www.beached.tv/assets/pause-c1c0a3d060f908372ebecf2eb7e7c018.svg");
this.is_playing = true;
var current_time = Math.round(new Date().getTime() / 1000);
if (current_time > gon.end_of_stream){
// location.reload();
}
}
}
</script>
onPlayerReady parameter event isn't accessible, because the function you are passing to your addEventListener is also using that variable name
So use another variable name, ex:
playButton.addEventListener("click", function(click_event) {
There's actually a bigger error. You want to use onPlayerStateChange's event to tell the you the state. Here's a working snippet:
var is_playing = false;
function onPlayerReady(event) {
var playButton = document.getElementById("play-button");
var that = this;
playButton.addEventListener("click", function(click_event) {
if (that.is_playing) {
player.pauseVideo();
}else {
player.playVideo();
}
});
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
this.is_playing = true;
}
}
For the current HTML5 player of youtube you can do this easily using:
document.getElementByTagName('video')[0].play()
document.getElementByTagName('video')[0].play()
I created a chrome extension here.
I am trying to change iframe source everytime user click on the skip button and it doesn't work.
var player;
window.onYouTubePlayerAPIReady = function() {
alert('called onYouTubePlayerAPIReady');
player = new YT.Player('header-video__video-element', {
events: {
'onStateChange': ShowMe
}
});
}
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function ShowMe() {
var sStatus;
sStatus = player.getPlayerState();
if (sStatus == -1) alert("Video has not started.");
else if (sStatus == 0) {
$('#ytplayer').replaceWith('<img class="special_hover" src="image" alt="" />')
}
else if (sStatus == 1) {
} //Video is playing
else if (sStatus == 2) {
}
else if (sStatus == 3) {
} //video is buffering
else if (sStatus == 5) {
} //Video is cued.
}
//CODE TRIGGERED BY BUTTON
$(this.settings.playTrigger).on('click', function(e) {
alert('changing source');
$("#header-video__video-element").attr('src', "https://www.youtube.com/watch?v=eozsR79JjPM");
//document.getElementById('header-video__video-element').setAttribute('src', "https://www.youtube.com/embed/eozsR79JjPM");
alert('changed');
//player.loadVideoById("95CX2VL0hVY");
// e.preventDefault();
// that.appendIframe();
});
The player.loadVideoById method that you commented out should do the work. Here is a working example of a little application I did
//Code from the YouTube iFrame API doc
//https://developers.google.com/youtube/iframe_api_reference
var player;
var id = "V13MbW3oMUw";
//Init API
window.onYouTubeIframeAPIReady = function() {
player = new YT.Player('player', {
height: '720',
width: '960',
videoId: "JxfzRNA2_8M",
events: {
'onReady': onPlayerReady,
}
});
};
// Launch video as it's ready
function onPlayerReady(event) {
event.target.playVideo();
}
//Change video onclick
$("#button").click(function(id){player.loadVideoById(id);});
I want to create one web player using youtube player api. I want to create auto play video.
For that I used following script:
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
var isPlaying = false;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '420',
width: '640',
playerVars: { 'autoplay': 1, 'controls': 0, 'showinfo': 0 },
events: {
// 'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopPlayerVideo() {
player.stopVideo();
return false;
}
function playPlayerVideo() {
player.playVideo();
return false;
}
function pausePlayerVideo() {
player.pauseVideo();
return false;
}
function ShowModalPopup() {
var url = $get("<%=hfURL.ClientID %>").value;
if (url != "") {
var fn = function () {
if(player != null)
$('#txtCnt').val(cnt + " : " + isPlaying + " :u " + url);
player.cueVideoById(url, 0, "hd1440");
player.playVideo();
$('#msg').hide();
$('#img_msg').hide();
isPlaying = true;
pendingDate = new Date();
pendingSec = 0;
}
setTimeout(fn, 1000);
$get("<%=hfDuration.ClientID %>").value = "";
$find("mpe").show();
}
return false;
}
function GetPlayTimeDuration() {
player.stopVideo();
player.clearVideo();
$get("<%=hfDuration.ClientID %>").value = $('#time').val();
//$find("mpe").hide();
if ($get("<%=hfDuration.ClientID %>").value == "") {
$get("<%=hfDuration.ClientID %>").value = "0";
}
isPlaying = false;
$('#time').val("");
$get("<%=hfURL.ClientID %>").value = "";
var UpdatePanel1 = '<%=upSubmit.ClientID%>';
if (UpdatePanel1 != null) {
__doPostBack('<%= btnClose.ClientID %>', '');
}
}
var cnt = 0;
setInterval(function () {
if (player != null) {
if (isPlaying) {
player.setPlaybackQuality('hd1440');
var tmptime = player.getCurrentTime();
tmptime = tmptime - ($('#<%= hfTimeFrame.ClientID %>').val() * tmptime);
$('#time').val(tmptime);
if (parseFloat($('#<%= hfCutoff.ClientID %>').val()) < parseFloat($('#time').val()))
GetPlayTimeDuration();
}
else if (!isPlaying) {
if ($get("<%=hfURL.ClientID %>").value != "") {
ShowModalPopup();
}
}
cnt++;
}
else {
player = new YT.Player('player', {
height: '420',
width: '640',
playerVars: { 'autoplay': 1, 'controls': 0, 'showinfo': 0 },
events: {
// 'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
}, 10);
my problem is that some time it so error:
Uncaught TypeError: undefined is not a function player.cueVideoById
"hd1440" is not one of the valid values you can set as the playback quality for cueVideoById. According to the documentation, the possible values are:
small
medium
large
hd720
hd1080
highres
default
In addition, the YouTube JavaScript Player API has been deprecated as of this year, so I wouldn't expect it to work the way you think it should.
Removed Unwanted Code DEMO
Hey,
I am implementing Youtube Video Player Api and i see some sort of error in console.
any how the video plays perfectly, but i want to know why the error is? if i keep the code outside of Skeleton Patterns, there wont be any error.
can someone please shade some light..
Thanks!!
JS :
(function($) {
$(function(){
var cVid, ytData1;
var callFlexSlider = ({
embedVideos : function(){
function explodeSlider(){
$('.sliderNew .flexslider').flexslider({
slideshow: false
});
$('.sliderNew #carousel, .sliderNew .flex-direction-nav').hide();
}
function explodeShow(){
$('.sliderNew .flexslider').flexslider({
slideshow: true
});
$('.sliderNew #carousel, .sliderNew .flex-direction-nav').show();
}
function getArtistId() {
return window.artist_id;
}
function loadPlayer() {
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() {
onYouTubePlayer();
};
}
}
var player;
function onYouTubePlayer() {
player = new YT.Player('player', {
height: '335',
width: '940',
videoId: getArtistId(),
playerVars: {
controls: 1,
showinfo: 0,
rel: 0,
showsearch: 0,
iv_load_policy: 3
},
events: {
'onStateChange': onPlayerStateChange,
'onError': catchError
}
});
}
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
done = true;
} else if (event.data == YT.PlayerState.ENDED) {
location.reload();
event.target.destroy();
}
}
function onPlayerReady(event) {
console.log('playerReady Event')
}
function catchError(event) {
if (event.data == 100) console.log("...");
}
function stopVideo() {
//alert('asdsad');
//player.destroy();
player.stopVideo();
explodeShow();
}
},
init : function(){
this.embedVideos();
}
});
callFlexSlider.init();
});
})(jQuery);
Call this loadPlayer(); inside document.ready function and try.
function loadScript() {
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);
}
}
function loadPlayer() {
window.onYouTubePlayerAPIReady = function() {
onYouTubePlayer();
};
}
$(function () {
loadScript();
})
you can always define it manually on the top of your script links :
<script type="text/javascript" id="www-widgetapi-script" src="https://s.ytimg.com/yts/jsbin/www-widgetapi-vflS50iB-/www-widgetapi.js" async=""></script>
<script src="https://www.youtube.com/player_api"></script>
This is the way how I managed to make the iframe api work:
function loadVideo() {
window.YT.ready(function() {
new window.YT.Player("video", {
height: "390",
width: "640",
videoId: "M7lc1UVf-VE",
events: {
onReady: onPlayerReady,
onStateChange: onPlayerStateChange
}
});
});
function onPlayerReady(event) {
event.target.playVideo();
}
function onPlayerStateChange(event) {
var videoStatuses = Object.entries(window.YT.PlayerState)
console.log(videoStatuses.find(status => status[1] === event.data)[0])
}
}
$(document).ready(function() {
$.getScript("https://www.youtube.com/iframe_api", function() {
loadVideo();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="video"></div>
I want to have a play / pause toggle button that controls my youtube video.
<a id="play-button">Play / Pause</a>
Right now it is just a link. This is the javascript code for the onPlayerReady function
function onPlayerReady(event) {
var playButton = document.getElementById("play-button");
playButton.addEventListener("click", function(event) {
if (event.data==YT.PlayerState.PLAYING) {
player.pauseVideo();
}else {
player.playVideo();
}
});
For some reason when I click the link it always does the else command. How can I get it to recognize that the video is currently playing? Is there a better way to do this play / pause toggle action?
SOLUTION for onPlayerStateChange
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.BUFFERING) {
event.target.setPlaybackQuality('hd1080');
}
if (event.data == YT.PlayerState.PAUSED) {
$("#play-button").attr("src", "http://www.beached.tv/assets/play-0a292db2c7cb500e5e768d0222ef1f94.svg");
this.is_playing = false;
}
if (event.data == YT.PlayerState.PLAYING) {
$("#play-button").attr("src", "http://www.beached.tv/assets/pause-c1c0a3d060f908372ebecf2eb7e7c018.svg");
this.is_playing = true;
}
}
FULL CODE
<div id="centerplayer">
<div id="player"></div>
<script>
var is_playing = false;
var fullscreen = false;
var live = true;
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '600',
width: '1067',
playerVars:{
autoplay: 1,
controls: 0,
rel: 0,
iv_load_policy: 3,
showinfo: 0
},
loadPlaylist:{
listType:'playlist'
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange,
'onError': onErrorDetect
}
});
}
function onErrorDetect(event){
if (event.data == 100) {
//video request was not found, error occurs when video has been removed or has been marked as private
event.target.nextVideo();
} else{
location.reload();
}
}
function onPlayerReady(event) {
event.target.setPlaybackQuality('default');
event.target.loadPlaylist(gon.playlist,gon.s_index,gon.s_time);
event.target.setLoop(true);
//PLAYER CONTROLS
var playButton = document.getElementById("play-button");
var that = this;
playButton.addEventListener("click", function(click_event) {
if (that.is_playing) {
$("#play-button").attr("src", "http://www.beached.tv/assets/pause-c1c0a3d060f908372ebecf2eb7e7c018.svg");
// if(live){
// var liveimg = document.getElementById('live-icon');
// liveimg.parentNode.removeChild(liveimg);
// live = false;
// }
player.pauseVideo();
}else {
$("#play-button").attr("src", "http://www.beached.tv/assets/play-0a292db2c7cb500e5e768d0222ef1f94.svg");
player.playVideo();
}
});
var muteButton = document.getElementById("mute-button");
muteButton.addEventListener("click", function() {
if(player.isMuted()){
$("#mute-button").attr("src", "http://www.beached.tv/assets/sound-2850c52028b16dd2c2e264c5dddb39ba.svg");
player.unMute();
}else{
$("#mute-button").attr("src", "http://www.beached.tv/assets/mute-8d50674fdbcdd2cc9597f009be41cea9.svg");
player.mute();
}
});
var enlargeButton = document.getElementById("enlarge-button");
enlargeButton.addEventListener("click", function() {
if (fullscreen){
$("#enlarge-button").attr("src", "http://www.beached.tv/assets/resize-enlarge-a44a4204dca596b45aacb25610ee3189.svg");
player.setSize(1067,600);
fullscreen = false;
}else{
$("#enlarge-button").attr("src", "http://www.beached.tv/assets/resize-shrink-f63cf0e6ab1eb2bb8f7223798c4fc9c5.svg");
player.setSize(1410,793);
fullscreen = true;
}
});
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.BUFFERING) {
event.target.setPlaybackQuality('hd1080');
}
if (event.data == YT.PlayerState.PAUSED) {
$("#play-button").attr("src", "http://www.beached.tv/assets/play-0a292db2c7cb500e5e768d0222ef1f94.svg");
this.is_playing = false;
if(live){
var liveimg = document.getElementById('live-icon');
liveimg.parentNode.removeChild(liveimg);
live = false;
}
}
if (event.data == YT.PlayerState.PLAYING) {
$("#play-button").attr("src", "http://www.beached.tv/assets/pause-c1c0a3d060f908372ebecf2eb7e7c018.svg");
this.is_playing = true;
var current_time = Math.round(new Date().getTime() / 1000);
if (current_time > gon.end_of_stream){
// location.reload();
}
}
}
</script>
onPlayerReady parameter event isn't accessible, because the function you are passing to your addEventListener is also using that variable name
So use another variable name, ex:
playButton.addEventListener("click", function(click_event) {
There's actually a bigger error. You want to use onPlayerStateChange's event to tell the you the state. Here's a working snippet:
var is_playing = false;
function onPlayerReady(event) {
var playButton = document.getElementById("play-button");
var that = this;
playButton.addEventListener("click", function(click_event) {
if (that.is_playing) {
player.pauseVideo();
}else {
player.playVideo();
}
});
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
this.is_playing = true;
}
}
For the current HTML5 player of youtube you can do this easily using:
document.getElementByTagName('video')[0].play()
document.getElementByTagName('video')[0].play()
I created a chrome extension here.