Lee Price
Lee Price

Reputation: 5212

YouTube iFrame API on dynamically created iFrame

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.

Upvotes: 3

Views: 1399

Answers (1)

Clayton Leis
Clayton Leis

Reputation: 1298

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"

(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');

  })

Upvotes: 0

Related Questions