Youtube iframe api loadVideoById () error

I am adding youtube videos to the companies website and would like them to appear on devices without flash memory. I played with the youtube iframe API and updated one of my examples to allow the user to click the link to change the video in the iframe. Modified Code:

<!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> <a href="javascript:loadVideo('kGIjetX6TBk');">Click me to change video</a> </body> </html> 

The only thing I added:

 function loadVideo(videoID) { if(player) { player.loadVideoById(videoID); } } 

This works fine in Safari, Chrome, and Firefox, but it doesn’t work in IE7, 8, or 9. In IE7 and 8, it returns the error "Object does not support this property or method."

Is this an API problem or am I doing something wrong?

+7
source share
3 answers

I had a similar problem, and it turned out that you should not call any of the methods of the YT.Player object (including loadVideoById ) until onPlayerReady was called.

Running an if(player) {...} check is not enough, a Player object will be created, and some properties will already be available without methods available.

+5
source

You will need to call the function to load the video from the onPlayerReady event.

For example, if you want to load a video when you click on a thumbnail, do it (this requires jquery, but it must get a point):

 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 that the player is loaded.

+3
source

Preventing clicks from spreading by return false after calling player.loadVideoById in my click event handler is a trick for me.

0
source

All Articles