Multiple instances of YouTube player inside loop - javascript

I have the following code, which works - but the part I can't figure out is how to grab the index in the onReady event. The result is 2,2 instead of 0,1 which I would expect - why?
Codepen
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 players = [];
var playerEl = document.querySelectorAll('.ytplayer');
function onYouTubeIframeAPIReady() {
for (var i = 0; i < playerEl.length; i++) {
players[i] = new YT.Player(playerEl[i], {
events: {
'onReady': () => { console.log('index: '+i) } // why doesn't this return 0,1 ??
}
});
}
}
<iframe class="video ytplayer" width="100%" height="390" type="text/html" src="https://www.youtube.com/embed/ScMzIvxBSi4?controls=0&t=31s&loop=1&playlist=ScMzIvxBSi4&showinfo=0&rel=0&enablejsapi=1" frameborder="0" allowfullscreen></iframe>
<iframe class="video ytplayer" width="100%" height="390" type="text/html" src="https://www.youtube.com/embed/iGpuQ0ioPrM?controls=0&t=31s&loop=1&playlist=iGpuQ0ioPrM&showinfo=0&rel=0&enablejsapi=1" frameborder="0" allowfullscreen></iframe>

I managed to solve it using the following code. The mistake I was making was I was trying to store a variable inside an event. The event is async and doesn't know that it's inside a loop - at least I think that's it, please correct me if I'm wrong.
Codepen working
function onYouTubeIframeAPIReady() {
document.querySelectorAll('.ytplayer').forEach((item) => {
new YT.Player(item, {
events: {
'onReady': (event) => {
event.target.playVideo();
event.target.mute();
}
}
})
})
}

Related

Cannot read property 'apply' of undefined - Youtube Api

I created the following code to make videos play on hover:
var player = [];
var el_number;
function onYouTubePlayerAPIReady() {
var players = $(".video");
for (var i = 0; i < players.length; i++) {
el_number = $(players[i]).parent().parent().index();
player[i] = new YT.Player(players[i], {
events: {
'onReady': onPlayerReady(i, el_number)
}
});
}
}
function onPlayerReady(number, elnumber) {
$(".article:eq("+elnumber+")").on({
'mouseover': function() {
player[number].playVideo();
},
'mouseout': function() {
player[number].pauseVideo();
}
});
}
<script src="https://www.youtube.com/iframe_api"></script>
<!-- Videos look like this: -->
<iframe class='video' src='https://www.youtube.com/embed/(video_id)?controls=0&showinfo=0&disablekb=1&fs=0&iv_load_policy=3&&enablejsapi=1' frameborder='0' allowfullscreen></iframe>
It works perfectly fine, but after some time of loading scripts it shows me this error in the console:
Uncaught TypeError: Cannot read property 'apply' of undefined www-widgetapi.js:65
at K.g.I (www-widgetapi.js:65)
at W.g.l (www-widgetapi.js:114)
at W.g.J (www-widgetapi.js:127)
at S.g (www-widgetapi.js:143)
at k (www-widgetapi.js:95)
I ckecked Opera and Edge there is no error. After disabling every extention there is still that problem in Chrome. What is the root of the problem here?
I think it's an issue with your callback definition :
onPlayerReady(i, el_number)
onPlayerReady takes the event data as parameter. To get the player, you can call event.target and store some data inside this object
For instance :
var player = [];
function onYouTubePlayerAPIReady() {
var players = $(".video");
for (var i = 0; i < players.length; i++) {
el_number = $(players[i]).parent().parent().index();
player[i] = new YT.Player(players[i], {
events: {
'onReady': onPlayerReady
}
});
player[i].el_number = el_number;
}
}
function onPlayerReady(event) {
console.log("event.target.el_number : " + event.target.el_number);
$(".article:eq(" + event.target.el_number + ")").on({
'mouseover': function() {
event.target.playVideo();
},
'mouseout': function() {
event.target.pauseVideo();
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.youtube.com/iframe_api"></script>
<!-- Videos look like this: -->
<iframe class='video' src='https://www.youtube.com/embed/B_hLfhccYf0?controls=0&showinfo=0&disablekb=1&fs=0&iv_load_policy=3&enablejsapi=1' frameborder='0' allowfullscreen></iframe>
You can find a jsfiddle here

Binding YouTube Video to Div Element from Seperate JS file

I have this problem embedding YouTube video in a PhoneJS single-page mobile application. In PhoneJS, the JS scripts are defined in a different file. So I defined the HTML div like this:
<div id="player"></div>
Now in the JS file, I did this:
function getVideo() {
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var playerDiv = document.getElementById('player');
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player(playerDiv, {
height: '250',
width: '444',
videoId: sIFYPQjYhv8
});
}
}
When I run and view the debugger, the call is made to Youtube and response is received, but it is not displayed on the view.
Ok since I am using KnockoutJS binding, I modified the div in the html view like this:
<iframe id="player" type="text/html" width="444" height="250" frameborder="0" data-bind="attr: { src: src }"></iframe>
And then pass in the src video id thus:
src: ko.observable('http://www.youtube.com/embed/' + sIFYPQjYhv8 + '?autoplay=1')
In this case however, in the debugger, the call is not even made to Youtube. Nothing just happens. Actually I prefer to use the API call instead of the second approach.
Any suggestions on how to make the first approach work? I mean using the API call?
EDIT
Just want to mention that when I add the code below in the view, the video is streamed alright.
<h1>Video</h1>
<div id="player"></div>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var playerDiv = document.getElementById('player');
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player(playerDiv, {
height: '250',
width: '444',
videoId: 'sIFYPQjYhv8'
});
}
</script>
I think the easiest way to do this is to use a custom binding handler with a flag set from the onYouTubeIFrameAPIReady callback
Sample jsFiddle
ko.bindingHandlers['player'] = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
// Check if global script and function is declared.
if ( !document.getElementById('playerScript') ) {
// Create script
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var playerDiv = document.getElementById('player');
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Create global function that their API calls back
window.playerReady = ko.observable(false);
window.onYouTubeIframeAPIReady = function() {
window.playerReady(true);
};
}
},
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var value = valueAccessor(),
id = value.id(),
height = ko.unwrap(value.height) || '250',
width = ko.unwrap(value.width) || '444'
;
if ( !value.id()) {
return;
}
if ( !window.playerReady() ) {
// YT hasn't invoked global callback. Subscribe to update
var subscription;
subscription = window.playerReady.subscribe( function(newValue) {
if ( newValue ) {
subscription.dispose();
// Just get this binding to fire again
value.id.notifySubscribers(value.id());
}
});
} else {
var player = new YT.Player( element, {
height: height,
width: width,
videoId: id
});
}
},
}
Now change your player div to
<div data-bind="player: { id: id, height: height, width: width }"></div>
Finally bind
var vm = {
id: 'sIFYPQjYhv8',
height: '250',
width: '444'
};
ko.applyBindings( vm )
EDIT
To remove the reliance on window, put your script tag that adds the new script element back, tweek as below, modify their callback and use a setTimeout instead of the "playerReady" observable
HTML Script
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
tag.setAttribute('id', 'playerScript');
tag.setAttribute('data-ready', 'false');
...
function onYouTubeIframeAPIReady = function() {
document.getElementById('playerScript').setAttribute('data-ready', 'true');
};
Player Binding
update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var value = valueAccessor(),
id = value.id(),
height = ko.unwrap(value.height) || '250',
width = ko.unwrap(value.width) || '444',
playerScript = document.getElementById('playerScript')
;
if ( !value.id()) {
return;
}
if ( !playerScript || playerScript.getAttribute('data-ready') !== 'true' ) ) {
// YT hasn't invoked global callback.
setTimeout( function() {
value.id.notifySubscribers(value.id());
}, 50);
} else {
var player = new YT.Player( element, {
height: height,
width: width,
videoId: id
});
}
}

Start youtube video on hover/mouseover

I'm trying to get youtube videos to start on hover. It will pause (not stop) when the user hovers over another video...
I am stuck on the hover command. Can someone help me work it out please?
The page has 16 videos, this is the working code from the jsfiddle that contains 3 videos as an example.
http://jsfiddle.net/sebwhite/gpJN4/
VIDEO:
<iframe id="player" width="385" height="230" src="http://www.youtube.com/embed/erDxb4IkgjM?rel=0&wmode=Opaque&enablejsapi=1;showinfo=0;controls=0" frameborder="0" allowfullscreen></iframe>
JAVASCRIPT:
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onStateChange': onPlayerStateChange
}
});
onYouTubeIframeAPIReady();
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
player1.pauseVideo();
player2.pauseVideo();
}
UPDATED FIDDLE
Try this:
var $$ = function(tagname) { return document.getElementsByTagName(tagname); }
function onYouTubeIframeAPIReady() {
var videos = $$('iframe'), // the iframes elements
players = [], // an array where we stock each videos youtube instances class
playingID = null; // stock the current playing video
for (var i = 0; i < videos.length; i++) // for each iframes
{
var currentIframeID = videos[i].id; // we get the iframe ID
players[currentIframeID] = new YT.Player(currentIframeID); // we stock in the array the instance
// note, the key of each array element will be the iframe ID
videos[i].onmouseover = function(e) { // assigning a callback for this event
if (playingID !== currentHoveredElement.id) {
players[playingID].stopVideo();
}
var currentHoveredElement = e.target;
if (playingID) // if a video is currently played
{
players[playingID].pauseVideo();
}
players[currentHoveredElement.id].playVideo();
playingID = currentHoveredElement.id;
};
}
}
onYouTubeIframeAPIReady();
Fiddle:
http://jsfiddle.net/gpJN4/3/

Using an array in Jquery

I'm not so experienced with Javascript and I have been struggling with this one pretty much all day.
I'm using Jquery to create and array of the ids of embedded youtube videos:
$(function() {
$('li').on("click",function(){
alert($(this).attr('data-pile'));
var pilename = $(this).attr('data-pile');
var videoIDs = [];
$("li[data-pile='"+pilename+"']").each(function(index){
videoIDs.push($(this).attr('id'));
});
$.each(videoIDs,function(){
});
});
});
And I need to use the array in this JS:
<script src="//www.youtube.com/iframe_api"></script>
<script>
/**
* Put your video IDs in this array
*/
var videoIDs = [
//my array of Ids here
];
var player, currentVideoId = 0;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '350',
width: '425',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.loadVideoById(videoIDs[currentVideoId]);
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
currentVideoId++;
if (currentVideoId < videoIDs.length) {
player.loadVideoById(videoIDs[currentVideoId]);
}
}
}
</script>
In each div where embedded videos are I'm applying an id with same id as video.
How should I make the two scripts work?
I'll really appreciate if someone can point me in the right direction.
You're declaring your videoIDs array twice, once in your click events and again in your second
script.
The one inside your click events is local to that function whereas the other one is global. Javascript has function scope, so that click event one gets discarded once that function ends.
If you remove the one inside your click events, I believe it should work. You should also remove the $.each... as I don't think it's going to help (you're trying to make a playlist, right?).
It should be noted that it's considered bad practice to pollute the global namespace by using global variables. If this is all the code you have on your page, it's probably not an issue.
Try doing it this way: add a custom listener after "click" event. Didn't check your array forming section, tested with a custom array, hope you won't have issues with it.
<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);
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '350',
width: '425',
});
}
$(function(){
$(document.body).on("click",".play", function(){
player.stopVideo();
var pilename = $(this).attr('data-pile');
var videoIDs = [];
$("li[data-pile='"+pilename+"']").each(function(index){
videoIDs.push($(this).attr('id'));
});
if(videoIDs.length > 0){
currentVideoId = 0;
player.loadVideoById(videoIDs[0]);
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
currentVideoId++;
if (currentVideoId < videoIDs.length) {
player.loadVideoById(videoIDs[currentVideoId]);
}
}
}
player.addEventListener("onStateChange", onPlayerStateChange)
player.playVideo();
}
});
});
</script>

handling multiple youtube videos

I have three youtube videos that I want to stop when the user click on a link link the page.
this is my code
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var youtubePlayer1;
var youtubePlayer2;
var youtubePlayer3;
function onYouTubeIframeAPIReady() {
youtubePlayer1 = new YT.Player('firstPlayer', {
});
youtubePlayer2 = new YT.Player('secondPlayer', {
});
youtubePlayer3 = new YT.Player('thirdPlayer', {
});
}
function stopVideo() {
if (youtubePlayer1 != null) {
youtubePlayer1.stopVideo();
}
if (youtubePlayer2 != null) {
youtubePlayer2.stopVideo();
}
if (youtubePlayer3 != null) {
youtubePlayer3.stopVideo();
}
}
This is the html code
<div id="blog">
<!--///////////// UN ORDERED LIST /////////////-->
<ul>
<!--///////////// LIST /////////////-->
<li>
<!-- iframe -->
<h3>
<strong>להקת קולות - בהרקדה חסידית...</strong></h3>
<br />
<iframe id="firstPlayer" width="800" height="485" src="http://www.youtube.com/embed/F0eR1KFkt58"
style="border:0" ></iframe>
<br />
<br />
<img src="images/bg3.PNG" alt="" /><p>
<span>תאור הוידאו: </span>טקסט אודות הוידאו, תאריך</p>
</li>
<!--///////////// SECOND IMAGE /////////////-->
<li>
<!-- iframe -->
<h3>
<strong>להקת קולות - בהרקדה ישראלית מוטרפת...</strong></h3>
<br />
<iframe id="secondPlayer" width="800" height="485" src="http://www.youtube.com/embed/mPTX4guU1W8"
style="border:0" ></iframe>
<br />
<br />
<img src="images/bg3.PNG" alt="" /><p>
<span>תאור הוידאו: </span>טקסט אודות הוידאו, תאריך</p>
</li>
<!--///////////// THIRD IMAGE /////////////-->
<li>
<!-- iframe -->
<h3>
<strong>להקת קולות - בואי בשלום...</strong></h3>
<br />
<iframe id="thirdPlayer" width="800" height="485" src="http://www.youtube.com/embed/E-_ONZOcScU"
style="border:0"></iframe>
<br />
<br />
<img src="images/bg3.PNG" alt="" /><p>
<span>תאור הוידאו: </span>טקסט אודות הוידאו, תאריך</p>
</li>
</ul>
</div>
when the user click on the link it calls the stopVideo function that cycle through all the players and stop them.
for some reason I can get it to work only on youtubePlayer2 object what am I doing wrong here?
Forgot to mention, when I debug the app using the chrome debugger I can see the the objects are defined and that the function is called.
I think that in this way works:
http://jsfiddle.net/ZLMF8/3/
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/swfobject/2/swfobject.js"></script></head>
<body>
<div id="ytplayer1">
<p>You will need Flash 8 or better to view this content.</p>
</div>
<div id="ytplayer2">
<p>You will need Flash 8 or better to view this content.</p>
</div>
<div id="ytplayer3">
<p>You will need Flash 8 or better to view this content.</p>
</div>
<script type="text/javascript">
var params = { allowScriptAccess: "always" };
swfobject.embedSWF("http://www.youtube.com/v/F0eR1KFkt58&enablejsapi=1&playerapiid=ytplayer1", "ytplayer1", "425", "365", "8", null, null, params);
swfobject.embedSWF("http://www.youtube.com/v/mPTX4guU1W8&enablejsapi=1&playerapiid=ytplayer2", "ytplayer2", "425", "365", "8", null, null, params);
swfobject.embedSWF("http://www.youtube.com/v/E-_ONZOcScU&enablejsapi=1&playerapiid=ytplayer3", "ytplayer3", "425", "365", "8", null, null, params);
function stop() {
if (ytplayer1) {
ytplayer1.stopVideo();
}
if (ytplayer2) {
ytplayer2.stopVideo();
}
if (ytplayer3) {
ytplayer3.stopVideo();
}
}​
</script>
Stop
</body>
</html>​
This code sample should work without issue, and in my testing it worked without flaw. Try making sure the script tag is added at the bottom of the page. This will help insure that the iframes are loaded by the time you make calls to them. Also try out http://www.youtube.com/html5 to see if that has a more reliable experience.
I don't see the need for the if statement if your code just runs on when not being able to find the youtubeplayer, but I once solved a problem similar by adding a else statement that made sure something would happen - which may explain why the above was only happening every now and then.
It only takes a little copy and paste.
function stopVideo() {
if (youtubePlayer1 != null) {
youtubePlayer1.stopVideo();
}
else {
youtubePlayer1.stopVideo();
}
if (youtubePlayer2 != null) {
youtubePlayer2.stopVideo();
}
else {
youtubePlayer2.stopVideo();
}
if (youtubePlayer3 != null) {
youtubePlayer3.stopVideo();
}
else {
youtubePlayer3.stopVideo();
}
}
Try this, its worked fine.
Note http:// is missing in src, because stackoverflow shows an error while posting with src. so correct it and test.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
tag.src = "//www.youtube.com/iframe_api";
Full working code
<!DOCTYPE HTML>
<html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<body>
<div id="firstPlayer"></div>
<div id="secondPlayer"></div>
<div id="thirdPlayer"></div>
<script>
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var youtubePlayer1;
var youtubePlayer2;
var youtubePlayer3;
function onYouTubeIframeAPIReady() {
youtubePlayer1 = new YT.Player('firstPlayer',{
height: '240',
width: '320',
videoId: 'F0eR1KFkt58',
events: {
'onReady': onPlayerReady1
}
});
youtubePlayer2 = new YT.Player('secondPlayer', {
height: '240',
width: '320',
videoId: 'mPTX4guU1W8',
events: {
'onReady': onPlayerReady2
}
});
youtubePlayer3 = new YT.Player('thirdPlayer', {
height: '240',
width: '320',
videoId: 'E-_ONZOcScU',
events: {
'onReady': onPlayerReady3
}
});
}
function onPlayerReady1(event) {
event.target.playVideo();
$('a').click(function(e) {
youtubePlayer1.stopVideo();
e.preventDefault();
});
}
function onPlayerReady2(event) {
event.target.playVideo();
$('a').click(function(e) {
youtubePlayer2.stopVideo();
e.preventDefault();
});
}
function onPlayerReady3(event) {
event.target.playVideo();
$('a').click(function(e) {
youtubePlayer3.stopVideo();
e.preventDefault();
});
}
</script>
<a>Stop</a>
</body>
</html>
Mohamed Navas' answer (first answer) helped me to come up with this:
<br>
<button id="pause">Pause</button>
<br>
<br>
<div id="firstPlayer"></div>
<div id="secondPlayer"></div>
<div id="thirdPlayer"></div>
<script>
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var youtubePlayer1;
var youtubePlayer2;
var youtubePlayer3;
function onYouTubeIframeAPIReady() {
youtubePlayer1 = new YT.Player('firstPlayer',{
height: '240',
width: '320',
videoId: 'qV9HxRU4ozY',
events: {
'onReady': onPlayerReady
}
});
youtubePlayer2 = new YT.Player('secondPlayer', {
height: '240',
width: '320',
videoId: 'nBRpWJ0QUH0',
events: {
'onReady': onPlayerReady
}
});
youtubePlayer3 = new YT.Player('thirdPlayer', {
height: '240',
width: '320',
videoId: 'E-_ONZOcScU',
events: {
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event) {
document.getElementById('pause').onclick = function() {
youtubePlayer1.pauseVideo();
youtubePlayer2.pauseVideo();
youtubePlayer3.pauseVideo();
e.preventDefault();
};
};
</script>
https://jsfiddle.net/tonhaoln/ancz2vkn/

Categories

Resources