YouTube video JavaScript stops working if put in dom ready function? - javascript

When I copy the youtube demo code exactly it works fine:
http://jsfiddle.net/czvufy75/1/
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<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: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
</body>
But as soon as I put it in a dom ready function nothings happens. Why is this?
http://jsfiddle.net/czvufy75/2/
$(function() {
// 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: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
$('.trigger').click(function(){
//this works
player.pauseVideo()
});
});

http://jsfiddle.net/czvufy75/4/
there is your problem: function onYouTubeIframeAPIReady() {...} is not executed because isn't found in global scope by iframe_api, here is a small fix :)
onYouTubeIframeAPIReady = function onYouTubeIframeAPIReady() {
console.log(done);
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}

Related

YouTube Iframe API - Play video on mobile

After searching and finding many similar questions, I can't find the correct answer. So I'm working with the YouTube Iframe API, and I know that autoplay etc. won't work for mobiles. And I have created a element that displays on mobiles, so when the user click that button, it should play the video. But I only get this message: "Try restarting your device if playback does not start soon".
var playElement = document.createElement("div");
playElement.style.display = "none";
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
playElement.style.display = "block";
}
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player(child, {
width: '100%',
height: '100%',
videoId: youtubeID,
playerVars: {
'iv_load_policy': 3,
'enablejsapi': 1,
'disablekb': 1,
'autoplay': 1,
'loop': 0,
'controls': 0,
'showinfo': 0,
'rel': 0,
'mode': 'transparent'
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
playElement.onclick = function() {
player.playVideo();;
};
Anyone that does have an actual working solution?
Remember player refers to a div with the ID 'player'. You can start with the example code on youtube api doc. It will autoplay when the video has loaded. You can add your playerVar options as well.
A note for mobile video autoplay. You can have it autoplay but it has to be muted. So you can try adding player.mute() when you it loads and setup a click handler to unmute it again if that is what you prefer.
<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<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: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
},
playerVars
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
</body>
</html>

Youtube's onStateChange is not fired if play is triggered by postMessage

If the youtube playVideo is triggered by postMessage, the onStateChange will not be fired. (http://jsfiddle.net/nedvedyy/smx92nq0/). Any one runs into it before?
<script src="jquery-1.10.2.min.js"></script>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<button class="button">BUTTON</button>
<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: '0Bmhjf0rKe8',
playerVars: {
'controls': 1
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
var playerReady = false;
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
playerReady = true;
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
function onPlayerStateChange(event) {
alert(event);
}
$(".button").on("click", function() {
document.getElementById('player').contentWindow.postMessage(JSON.stringify({
'event': 'command',
'func': 'playVideo',
'args': []
}), "*");
});
</script>
Strangely, if the playVideo is called like below, the onStageChange can be captured.
onPlayerReady=function(event) {
console.log("hey Im ready");
event.target.playVideo();
}
Did you complete your homework here? Go through complete manual, your solution is there from where you pasted.
https://developers.google.com/youtube/iframe_api_reference

Rails & Youtube API: Issues loading iframe

I'm trying to implement the Youtube Iframe API into my Rails app. I'm trying to replicate the exact example on the Youtube Iframe API instructions page.
Created a yt_player.js file:
$(function() {
alert('this gets called')
// 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() {
alert('this does not get called')
player = new YT.Player('player-wrapper', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
});
And my view:
<div id="player-wrapper"></div>
I was expecting this to work but no video is being loaded. No errors showing in console.
What am I doing wrong?
First of all, I'm pretty sure your window.player and window.onYouTubeIframeAPIReady are undefined when you check in the browser console.
The reason is the way youtube iframe api work, those above variables must be defined globally.
Let check this document
They say:
The onYouTubeIframeAPIReady function will execute as soon as the player API code downloads. This portion of the code defines a global variable, player, which refers to the video player you are embedding, and the function then constructs the video player object.
So the changes will be: (define youtube variables and callbacks globally)
// Your current code
window.player = null; // <-- change here
window.onYouTubeIframeAPIReady = function() { // <-- change here
alert('this does not get called')
player = new YT.Player('player-wrapper', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
window.onPlayerReady = function(event) { // <-- change here
event.target.playVideo();
}
window.done = false; // <-- change here
window.onPlayerStateChange = function(event) { // <-- change here
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
window.stopVideo = function() { // <-- change here
player.stopVideo();
}

YouTube API to play random video from tag

I have YouTube API which I got from this link...
https://developers.google.com/youtube/iframe_api_reference
It's working okay, but I am looking for a way for it to play a random video based on a tag...is this possible? Is there a tutorial on it?
Here is my code
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<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: 'u1zgFlCw8Aw',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
Make Ajax function call to handle the request
function request_yt_videoID(vid)
{
// Some Code
player.loadVideoById(vid);
}
Visit Google Developer Site: https://developers.google.com/youtube/iframe_api_reference#loadVideoById

Youtube iframe player doesn't embed using Youtube's Player API

I am referring to the example code provided by Youtube seen below. The sample code is suppose to ....
The sample HTML page below creates an embedded player that will load a
video, play it for six seconds, and then stop the playback.
<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "//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: 'u1zgFlCw8Aw',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
</body>
</html>
Here's jsFiddle link for the code above.
Can you tell why this isn't working?

Categories

Resources