0

I have a youtube iframe video, and I want to close it when it ends. This should be working, but it is not. The fancybox launches and the video displays correctly, but none of the console.log appears. What am I doing wrong?

        $.fancybox({
          href: "https://www.youtube.com/embed/8CR-zM6jwD8?rel=0&autoplay=1",
          type: "iframe",
          beforeShow: function () {
              // Find the iframe ID
              var id = $.fancybox.inner.find('iframe').attr('id');
              // Create video player object and add event listeners
              var player = new YT.Player(id, {
                  events: {
                      'onStateChange': function (event) {
                        console.log('onStateChange fired');
                          if (event.data === 0) {
                              console.log('ended');
                              $.fancybox.close();
                          } // if
                      } // onStateChange
                  } // events
              }); // YT.Player

              loadPage();
          }, // beforeShow
      }); // fancybox

JSFIDDLE

pablito.aven
  • 1,135
  • 1
  • 11
  • 29

1 Answers1

3

onStateChange return an event, But is not possible access directly. you need onReady too. And i remove the end of your extension video autoplay=1 and replace by enablejsapi. Work fine now

Please try: http://jsfiddle.net/d6egj2sq/

P. Frank
  • 5,691
  • 6
  • 22
  • 50
  • Great! This works. Why does it need to have `onReady` event too? And what and why are `&enablejsapi=1&wmode=opaque` parameters? What do they do and why do I need them for this to work? – pablito.aven Nov 13 '15 at 18:55
  • 1
    If you add autoplay in url, your vidéos play auto because is a parameter but is not `YT.player` who play this. `onReady` get when your `YT.player ` completly charged videos. When is charged, the play function is activated. The parameter ¤enablejsapi` is for get api response. – P. Frank Nov 13 '15 at 19:42