YouTube iFrame API for dynamically generated iFrame
I am using the YouTube iFrame API because I need to pause a video dynamically generated with jQuery. I have the following code:
// Load YouTube API
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
$(function() {
var player;
$(document).on('click', 'button', function(){
media = $(this).data('media');
$('#player').append('<div id="media"><iframe width="200" height="200" src="http://www.youtube.com/embed/' + media + '?autoplay=1" frameborder="0" allowfullscreen id="media-player"></iframe>');
var player = new YT.Player('media-player');
})
$('#pause').click(function(){
player.pauseVideo();
});
}
However I am getting this error: Uncaught TypeError: Cannot read property "pauseVideo" from undefined
Can anyone point me in the right direction. Any help is appreciated.
+3
source to share
1 answer
You have redefined "player" as a local variable on the first click callback, again using the "var" keyword. Get rid of the second "var"
(function() {
var player;
$(document).on('click', 'button', function(){
media = $(this).data('media');
$('#player').append('<div id="media"><iframe width="200" height="200" src="http://www.youtube.com/embed/' + media + '?autoplay=1" frameborder="0" allowfullscreen id="media-player"></iframe>');
player = new YT.Player('media-player');
})
0
source to share