Pass youtube iframe api events onstatechange when src changes - javascript

So I figured I would update this with a working example. I have ditched stating the iframe tag and just used the iframe api to create an iframe and then loaded the player by id with a data attribute. Here is a working example below. So now all statechanges are passed consistently through the youtube player. So the script will load an iframe into the Div #player and you can just loadVideoByID pretty easily with jquery and javascript.
<div id="player"></div>
<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;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
playerVars: { 'autoplay': 0,},
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
alert('started');
}
function onPlayerStateChange(event) {
if(event.data === 0) {
alert('done');
}
}
$( document ).on( "click", ".video-link", function(e) {
e.preventDefault();
var videoID = $(this).attr('data-videoID');
player.loadVideoById(videoID);
});
</script>
And then use a link with a data-attribute like so.
Link

Rather than having buttons to play, why not cue to playlist when the player is ready? You can hold the video ID's in an array... If this isn't what you're looking for just leave a comment below and I will change things the best I can to fit.
//Array of videos
var MyVideos=["E6RGMRamAFk","IHQr0HCIN2w","CogIXrea6A4"];
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 onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
//Player is ready, cue the array of videos into the playlist.
player.cuePlaylist(MyVideos);
}
function onPlayerStateChange(event) {
}
JS Fiddle - Working Demo
YouTube JavaScript Player API Reference
If you have any questions please leave a comment below and I will get back to you as soon as possible.
I hope this help. Happy coding!

Related

YouTube IFrame API with existing IFrame failing to run callbacks

Somewhat related to:
YouTube IFrame API doesn't always load?
But different in that I AM loading the YouTube script per instructions. Note, in my source, the iframe is ABOVE the script block in the load order. I based this off of these instructions (below). The example works fine if I'm on that page, but doesn't seem to work for me when I put the code on mine. I'm sure I'm missing something really simple but I'm to be missing it. Thanks!
https://developers.google.com/youtube/iframe_api_reference#Mobile_considerations
var tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
//Console shows this script is loading
var player;
function onYouTubeIframeAPIReady() {
console.log("onYouTubeIframeAPIReady", arguments); //This shows in console
player = new YT.Player('js_youTubeFrame', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
console.log("onPlayerReady",event); //Never triggers
}
function onPlayerStateChange(event) {
console.log("onPlayerStateChange", event); //Never triggers
if (event.data === YT.PlayerState.PLAYING) {
console.log("YouTube Video is PLAYING!!"); //Never triggers
}
}
<div id="js_youTubeContainer" class="embed-responsive embed-responsive-16by9">
<iframe id="js_youTubeFrame" class="embed-responsive-item" src="https://www.youtube-nocookie.com/embed/u3A7bmEOtaU?enablejsapi=1&rel=0&showinfo=0" frameborder="0" allowfullscreen></iframe>
</div>
Best way to load a Youtube Video by his API, is following this sintaxis:
<div id="video-youtube"></div>
<script id="youtube-tracking-script">
var youtubeVideoId = 'u3A7bmEOtaU'; // replace with your own video id
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementById("youtube-tracking-script");
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var video;
function onYouTubeIframeAPIReady() {
video = new YT.Player('video-youtube', {
height: '352',
width: '100%',
videoId: youtubeVideoId,
playerVars: {rel: 0, showinfo: 0},
events: {
'onStateChange': videoPlay
}
});
}
function videoPlay(event) {
if (event.data == YT.PlayerState.PLAYING) {
console.log("YouTube Video is PLAYING!!");
}
if (event.data == YT.PlayerState.PAUSED) {
console.log("YouTube Video is PAUSED!!");
}
if (event.data == YT.PlayerState.ENDED) {
console.log("YouTube Video is ENDING!!");
}
}
</script>
https://jsfiddle.net/t4qwfk0d/1/
You should replace your <iframe> </iframe> to <div id= "js_youTubeFrame"> </div>, in my case it works.
I think that Youtube Iframe Api needs that div to convert it on iframe after.

How do I get the YouTube API to load onclick?

I am using the YouTube Iframe as shown below. I want to make my player load on the click of a button instead as soon as the API loads.
I have created a system where a user of my website will be able to choose what videos will be loaded into the playlist, so I cannot hardcode the YouTube video IDs. Is it possible to make an onclick function that fires an event that loads the player? If so, how??
Thanks so much!!!
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: { //CAN I REPLACE THE ONREADY EVENT WITH ONE
'onReady': onPlayerReady, //THAT FIRES ONCLICK?
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
You can do something like code below
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 video_id = '' //Desired video ID
var player;
$('LOAD_BUTTON').on('click', function() {
// Load player when LOAD_BUTTON is clicked
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: video_id,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
});
function onPlayerReady(event) {
$('PLAY_BUTTON').on('click', function() {
// Play video when PLAY_BUTTON is clicked
event.target.playVideo();
});
}

Unmute youtube video bootstrap [duplicate]

I'm experimenting with the Youtube player but I can't get it to mute by default.
function onPlayerReady() {
player.playVideo();
// Mute?!
player.mute();
player.setVolume(0);
}
How do I mute it from the start?
Fiddle
Update:
JavaScript Player API is deprecated.
Use iframe Embeds instead.
Turns out player.mute() works fine. It only needed the parameter enablejsapi=1. Initial test in the fiddle didn't work because the player initiation had an error. The following works.
HTML:
<iframe id="ytplayer" type="text/html" src="https://www.youtube-nocookie.com/embed/zJ7hUvU-d2Q?rel=0&enablejsapi=1&autoplay=1&controls=0&showinfo=0&loop=1&iv_load_policy=3" frameborder="0" allowfullscreen></iframe>
JS:
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('ytplayer', {
events: {
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event) {
player.mute();
player.playVideo();
}
Fiddle
Credit to Gagandeep Singh and Anton King for pointing to enablejsapi=1
All above answers didn't work for me for some reason. It might be weird wordpress theme that I had to use or depreciated methods at Youtube API, I'm not sure. The only way of muting the player was to insert the code below into tag.
// Loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Replaces the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('ytplayer', {
height: '390',
width: '640',
videoId: 'YOUR_VIDEO_ID',
playerVars: {
autoplay: 1,
controls: 1,
disablekb: 1,
hl: 'ru-ru',
loop: 1,
modestbranding: 1,
showinfo: 0,
autohide: 1,
color: 'white',
iv_load_policy: 3,
theme: 'light',
rel: 0
},
events: {
'onReady': onPlayerReady,
}
});
}
function onPlayerReady(event){
player.mute();
}
<div id="ytplayer"></div>
It's important to note that YouTube API mandates you run this within your markup directly within a <script> tag, or via a standard document.onLoad() native listener and not as a named function.
Otherwise it will not natively bind the onYouTubeIframeAPIReady() function to the DOM.
Try below code
var youtubeplayer = iframe.getElementById('ytplayer');
youtubeplayer .setVolume(0);
And below is your fiddle updated version,
NOTE: Must include enablejsapi=1 in video url
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('ytplayer', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
player.playVideo();
// Mute?!
//player.mute(); instead of this use below
event.target.mute();
//player.setVolume(0);
}
DEMO
Hope this helps...

setinterval stop working when I change youtube video

zzz=setInterval(function(){document.getElementById('bugbox').value =
player.getCurrentTime()}, 1000);
I play the video and I see the time in bugbox
When I click the button the video loads but setInterval don't show player.getCurrentTime(); in bugbox
onclick="document.getElementById('player').src='http://www.youtube.com/watch_popup?v=vt4X7zFfv4k'
First video is loaded from this code:
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
idv='qV5lzRHrGeg';
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: idv,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
Edit:
Solved!
I use #NewToJS solution from the comment.

Youtube Player won't start upon setTimeout, help needed

I have followed the Youtube API while constructing a player. I need to to call the autoplay function via javascript but it won't listen to the setTimeout function, and it won't start playing:
Could someone light me up where am I wrong?
Regards!
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
}
});
}
function onPlayerReady(event){
setTimeout(function(){
playVideo();
},5000);
}
As you are declaring player variable and later set it to instance of YT.Player, you have to use the same variable on setTimeout too.
setTimeout(function(){
player.playVideo();
},5000);

Categories