how to start an embeded video with the youtube iframe-api - javascript

I am new to coding and I am trying to learn how to use the youtube IFRAME to control embded videos. The following code is mostly from youtube's api documentation. The only thing I added were the buttons and event listeners that are attached to them.
Can someone explain to me why "play" button that I have created can't start the video?
// 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: '250',
width: '300',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
document.getElementById('pause').onclick = function() {
player.pauseVideo();
};
document.getElementById('play').onclick = function() {
player.playVideo();
};
<html>
<body>
<div><button id= "pause">Pause</button></div>
<div><button id= "play">Play</button></div>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
</body>

It seems that the documentation of the iFrame API is either outdated or completely wrong.
The function which should initialize the player onYouTubeIframeAPIReady() will never fire thus a click on the play/pause buttons won't work because the variable player is undefined.
To workaround this, you have to wait until the script you're loading into the freshly created <script> element has finished loading and inside the callback function you need to initialize the YT component by a call to it's own ready() function. This isn't mentioned anywhere.
Well, get rid of the complete onYouTubeIframeAPIReady function and replace it with this:
tag.onload = function() {
YT.ready(function() {
player = new YT.Player('player', {
height: '250',
width: '300',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
}
});
});
};

Related

Add video to page using YouTube Player API

I want to load a YouTube video on a button click using the Player API. The goal is that a user can input a video url, click a button, and then the video loads below (I excluded the form input below to make it a little simpler).
I've tried using location.reload(); to force reload the page, and checked out some other similar questions which aren't entirely helpful because they don't use the API (which I need to use for later when functionality added)
This example from the docs works fine:
<!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
}
});
}
// 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>
I want to get something like this (very similar version) to work. I'm not sure why it doesn't currently.
<!DOCTYPE html>
<html>
<body>
<input type="submit" value="Submit" id="submit">
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
document.getElementById("submit").addEventListener("click", function() {
location.reload();
// 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>
</html>
You have two issues.
1) onYouTubeIframeAPIReady is never called because it is defined after the youtube API loads. You can see this by adding a console.log.
2) When you reload the page, the page reloads; i.e. your previous variables and video and everything are gone.
Here's a minimal example to load & play a youtube video on button click:
<input type="submit" value="Submit" id="submit">
<div id="player"></div>
<script src="https://www.youtube.com/iframe_api"></script>
<script>
document.getElementById('submit').addEventListener('click', () => {
new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
onReady: e => e.target.playVideo()
}
});
});
</script>
Note, the youtube code samples are either trying to be backwards compatible or just haven't been rigorously updated. They don't follow modern styles (e.g. they use var instead of let, == instead of ===, " instead of ', etc.

Javascript play youtube API (+queue videos)

Basically, i alrdy managed to create a website to search for videos using the youtube video api.
I would like now to add a youtubevideo player (iframe?), and possibly be able to queue videos (url) from a text input.
My next question, i found on the internet the required code for using an iframe,
but the script is all in html page, and i was wondering if it was possible to place the code in my JS page.. i tried it, but doesn't work... I thought that placing the syntaxes between & in my js file would do it...
Can someone explain how i can make it work while placing the code in my js file?
I know it's prboably a stupid question...
Thanks a lot!
<html>
<body>
<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>
</html>
i tried it the following way;
in html:
<script src="js/app.js"></script>
in js;
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
..... etc
}

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

simple Youtube iframe API right out of the documentation, what am I doing wrong?

http://jsfiddle.net/y2Y5k/
I'm trying to make a simple youtube player with the javascript API and I'm doing something wrong.
In that fiddle, Im just using the exact code snippets from the documentation provided by google.
I loaded the api as a source.
I placed a div with the id 'player'.
What did I do wrong here?
<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>
It is because Fiddle. All JavaScript you put in there is encapsulated in other functions (probably window.onload or something).
Therefore Youtube can't get to your onYouTubeIframeAPIReady function.
Just try this outside Fiddle. It will work.
On the top left side, from Frameworks & Extensions, select No wrap - in instead of onLoad.
That will give you the result as expected.

How do I have a popup/popover appear when a YouTube video finishes?

I am trying to figure out a way to trigger a javascript modal popup/popover when a YouTube video finishes.
I first saw this achieved on UpWorthy.com. See this video for an example when the video ends: http://www.upworthy.com/bully-calls-news-anchor-fat-news-anchor-destroys-him-on-live-tv
I have enabled the javascript api by adding the JS parameter to the embed code (enablejsapi=1)
I am using this Simple Modal script to achieve the modal: http://www.ericmmartin.com/projects/simplemodal/
How do I get the end of the youtube video to trigger it?
Many thanks
<html>
<head>
<title>YT Test</title>
<script type="text/javascript">
<!--
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "http://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: 'ecccag3L-yw',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// The API will call this function when the video player is ready.
function onPlayerReady(event) { /* do nothing yet */ }
// The API calls this function when the player's state changes.
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
// insert appropriate modal (or whatever) below
alert('I hope you enjoyed the video')
}
}
-->
</script>
</head>
<body>
<div id="player"></div>
</body>
<html>
Use the onStateChange event of the Youtube Player and check the current player state. If the state is YT.PlayerState.ENDED then you can trigger the modal dialog box.
From Youtube JavaScript player api reference document(with some modification)
function onYouTubePlayerReady(playerId) {
ytplayer = document.getElementById(playerId);
ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}
function onytplayerStateChange(newState) {
if(newState==YT.PlayerState.ENDED){
//OPEN Modal dialog box here
}
}

Categories

Resources