youtube iframe api loadVideoById() error - iframe

I am adding youtube video to a companies website and would like them to display on non-flash devices. I have been playing with the youtube iframe API and updated one of their examples to allow a user to click on a link to change the video in the iframe. The edited code is:
<!DOCTYPE HTML>
<html>
<body>
<div id="player"></div>
<script>
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var done = false;
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'JW5meKfy3fY',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(evt) {
evt.target.playVideo();
}
function onPlayerStateChange(evt) {
if (evt.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
function loadVideo(videoID) {
if(player) { player.loadVideoById(videoID); }
}
</script>
Click me to change video
</body>
</html>
The only thing I added was:
function loadVideo(videoID) {
if(player) { player.loadVideoById(videoID); }
}
This works fine in Safari, Chrome and Firefox but does not work in IE7, 8 or 9. In IE7 and 8 it returns an error "Object does not support this property or method".
Is this an issue with the API or am I doing something wrong?

I had a similar problem, and it turned out that you shouldn't call any of the methods on the YT.Player object (including loadVideoById) as long as onPlayerReady hasn't been called.
Doing a check if(player) {...} isn't sufficient, the Player object will be created and some properties will already be available in out without the methods you need being available.

You will need to call the load video function from the onPlayerReady event.
For example, if you want to load a video when clicking a thumbnail do this (this would require jquery but it should get the point across):
function onPlayerReady(evt) {
evt.target.playVideo();
//declare the click even function you want
$('#thumbs a).click(function(){
//get a data-video-id attr from the <a data-video-id="XXXXXX">
var myvideo = $(this).attr('data-video-id');
//call your custom function
loadVideo(myvideo);
//prevent click propagation
return false;
});
}
This way you can be sure the player is loaded.

Preventing click propagation with return false after the call to player.loadVideoById in my click event handler did the trick for me.

Related

Youtube video as background for specific section

I need to make a youtube video as a background for a specific section not the whole page.
So I need for section to be 390px height and 100% width.
Right now I am using this code but the problem is that the youtube iframe is 100% full width but the video itself is very small and with black sidebars.
here is the code:
<div class="video-wrapper">
<div id="player"></div>
</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: '100%',
videoId: 'EhArkyWXpO0',
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>
I am using youtube API and Im setting 100% width in javascript.
I am pretty sure I have to use css to achieve this, but no success so far...
Here is the current output
My desired output would be the wideo without black sidebars
Thanks!
You need to adjust the width with javascript by settings width to the width of your window or the parent node.
Set the size of the parent node to 100% and try something like:
node = document.getElementById("player");
player = new YT.Player('player', {
height: node.parentNode.offsetWidth * 9 / 16,
width: node.parentNode.offsetWidth,
videoId: 'EhArkyWXpO0',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
)
If you want to adjust the size if the window is resized, you have to add a function to window.onresize:
window.onresize = function() {
var node = document.getElementById('player');
// fetch player; may a childnode of node[id="player"]
player.setAttribute("width", node.parentNode.offsetWidth);
};

Problems with Youtube Iframe Api to start playing video on Chrome

I have following starting setup:
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
Then in onPlayerReady handler I added event listener to button which is outside iframe:
function onPlayerReady(event) {
button.addEventListener('click', () => event.target.playVideo());
}
In onPlayerStateChange I'm just logging what is happening:
function onPlayerStateChange(event) {
console.log(event.data);
}
After hitting that button in Chrome (v.72.0.3626.119) there are 3 entries in console: -1 (UNSTARTED), 3 (BUFFERING), -1 (UNSTARTED). When I try to hit button again nothing happens.
This works perfectly in Firefox, IE giving in console: -1 (UNSTARTED), 3 (BUFFERING),1 (PLAYING) and simply video starts playing.
Do you have any idea how to solve it?
You have to add in the onPlayerReady function this line:
event.target.playVideo();
As is shown in the documentation:
Example:
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
I can't say for sure why, but, in Google Chrome, for autoplay the video, you need to set the value 1 to the mute parameter, otherwise, autoplay the video wont work.
Example:
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '360',
width: '640',
videoId: '<YOUR_VIDEO_ID>',
playerVars: {
'autoplay': 1,
'loop': 1,
'mute': 1 // N.B. here the mute settings.
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
You can check this jsfiddle for guide yourself how you can set custom controls for play/pause your embed video.
I have sent a key after load html, and it works for me.
KeyEvent k = new KeyEvent();
k.WindowsKeyCode = 0x0D;
k.FocusOnEditableField = true;
k.IsSystemKey = false;
k.Type = KeyEventType.Char;
webytb.GetBrowser().GetHost().SendKeyEvent(k);
From this answer, Google Chrome need the allow="autoplay" attribute on iframe to let JS controls the player or make auto play function work.
This is required if you manually use <iframe> instead of <div> tag.
Example:
Attention! Please note that it maybe not work if the result iframe of this site don't have allow="autoplay" attribute on iframe. Copy and paste HTML & JavaScript into your .html file is the best way to test that it is really working.
var player;
/**
* Load YouTube API JavaScript
*/
function loadYTAPIScript() {
console.log('loading YouTube script.');
let tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
}
/**
* On YouTube iframe API ready
*
* This function will be called automatically by YouTube.
*/
function onYouTubeIframeAPIReady() {
console.log('function `onYouTubeIframeAPIReady` was called.');
player = new YT.Player('player', {
events: {
'onError': onError,
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onError(event) {
console.error('YouTube API error!', event);
} // _onError
/**
* On player ready.
*
* This is callback function from `onReady` event in `onYouTubeIframeAPIReady()`.
*/
function onPlayerReady(e) {
console.log('function `onPlayerReady` was called from `onReady` event callback.', e);
listClickButtons();
}
/**
* On player state change.
*
* This is callback function from `onStateChange` event in `onYouTubeIframeAPIReady()`.
*/
function onPlayerStateChange(e) {
console.log('function `onPlayerStateChange` was called from `onStateChange` event callback.', e);
let state = e.target.getPlayerState();
let stateText = '';
if (state === -1) {
stateText = 'unstarted';
} else if (state === YT.PlayerState.ENDED) {
stateText = 'ended';
} else if (state === YT.PlayerState.PLAYING) {
stateText = 'playing';
} else if (state === YT.PlayerState.PAUSED) {
stateText = 'paused';
} else if (state === YT.PlayerState.BUFFERING) {
stateText = 'buffering';
} else if (state === YT.PlayerState.CUED) {
stateText = 'cued';
}
console.log('State text: ', stateText);
}
/**
* Listen on click buttons to controls the video.
*
* This method was called from `onPlayerReady()`.
*/
function listClickButtons() {
console.log('Listen click buttons.');
let isPlayed = false;
let playpauseBtn = document.getElementById('yt-playpause');
let stopBtn = document.getElementById('yt-stop');
playpauseBtn.addEventListener('click', (e) => {
e.preventDefault();
console.log('User click on play/pause button.');
if (isPlayed === false) {
player.playVideo();
isPlayed = true;
} else {
player.pauseVideo();
isPlayed = false;
}
});
stopBtn.addEventListener('click', (e) => {
e.preventDefault();
console.log('User click on stop button.');
player.stopVideo();
});
}
document.addEventListener('DOMContentLoaded', (e) => {
console.log('DOM ready.');
loadYTAPIScript();
});
<iframe id="player"
width="560" height="315"
src="https://www.youtube.com/embed/1L904pgYbOE?enablejsapi=1"
title="YouTube video player"
allow="autoplay"
allowfullscreen=""
></iframe>
<!--
The `iframe` URL (`src` attribute) must contain enablejsapi=1 query string to let JS API work.
The `iframe` must contain `allow="autoplay"` attribute to allow JS controls the player.
-->
<div class="yt-controllers">
<button id="yt-playpause" type="button">
Play/Pause
</button>
<button id="yt-stop" type="button">
Stop
</button>
</div>
See full code on jsfiddle.
Reference:
Iframe
Iframe allow features list
YouTube Iframe API

Hide youtube annotations

I'm a french designer (so, sorry for my english mistakes) and I'm trying to create an interactive video with different videos hosted on youtube.
These videos already use the youtube 'annotations' or 'cards', but I want to hide them to create my own solution.
Basically I just want to show two divs at a certain timecode of the video to allow user to click on one of them to go to a new url. This thing works.
My question is simple : how can I hide the existing annotations?
I've tried with css, but it doesn't seem to work…
I'm not a full-time developer, so if you know a simple solution, I would be happy to know it :)
Here is the code
<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', {
height: '360',
width: '640',
videoId: 'mVwQFmKc7mA',
playerVars: { 'autoplay': 1, 'controls': 1, 'rel': 0, 'showinfo': 0, 'iv_load_policy': 3 },
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(displayNewDivs, 2000);*/
done = true;
}
}
function displayNewDivs() {
// HERE THE CODE TO SHOW NEW DIVS
}
</script>
Thank you very much!

onReady event not firing on IE11

onReady event are not being fired on IE11 & Edge, but it's working fine on IE10, Firefox, Safari and Google Chrome.
I'm using the javascript api to mute a video when the page is loaded.
This is the code i wrote. (Note. I'm using Drupal)
(function ($) {
function onPlayerReady(event) {
event.target.mute();
}
function muteVideos(video_ids) {
for (var iframe_id in video_ids) {
var player = new YT.Player(iframe_id, {
videoId: iframe_id,
playerVars:
{
"enablejsapi":1,
"origin":document.domain,
"rel":0
},
events: {
"onReady": onPlayerReady
}
});
}
}
function loadPlayer(video_ids) {
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 () {
muteVideos(video_ids);
};
} else {
muteVideos(video_ids);
}
}
Drupal.behaviors.eweev_media_youtube_video = {
attach: function (context, settings) {
// Array containing iframe ids of the youtube videos that should be
// muted provided using drupal_add_js
var video_ids = Drupal.settings.eweev_media_youtube_video;
loadPlayer(video_ids);
}
};
})(jQuery);
I wanna know if i'm missing something.
I did some research and found out that there is a temporary issue with the IFrame API.
For temporary fix, you may view the related Stack overflow below:
YouTube iframe player API - OnStateChange not firing and Youtube Iframe API not working in Internet Explorer (11)

ASP.NET <Body onload="initialize()">

I am creating an ASP.NET custom control.
I want to set the body onload event of the ASPX page where the control resides.
Please note I cannot rely on the body tag in the ASPX page having runat="server".
any ideas??
Cheers.
Inline javascript! Just incase you can't use jQuery
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function')
{
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
} } }
addLoadEvent(initialize);
link to read http://www.webreference.com/programming/javascript/onloads/
Credits goto http://simonwillison.net/
If you include jQuery in your project you can use this:
jQuery(document).ready(function ()
{
// page load code here
});
You can run these multiple times on a page, ie handy within a control
Try this,
<script type="text/javascript">
window.onload = initialize();
function initialize() {
//your stuff
}
</script>

Resources