I'm using the YouTube iFrame API because I need to be able to pause a video dynamically created 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'm getting this error: Uncaught TypeError: Cannot read property 'pauseVideo' of undefined
Can anyone point me in the right direction. Any help is appreciated.
You re-defined "player" as a local variable to the first click callback by using the keyword "var" again. Get rid of the second "var"