0

I am trying to get a "pause" event with the YouTube API on a YouTube video created by AMP (Accelerated Mobile Pages) with this basic example: https://ampbyexample.com/components/amp-youtube/

The code works and I get a video showing. The next thing I wanted to do was do something when the video is paused. I've had a look on how to do this and I've got the current code:

//The iframe generated from AMP does not give an ID so I have added one
$('#AMP_1 iframe').attr('id', 'yt_player');

//Load API code
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;
 function onYouTubeIframeAPIReady() {
  player = new YT.Player('yt_player', {
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
}

function onPlayerReady() {
  console.log("READY");
}

function onPlayerStateChange() {
  console.log("STATE CHANGE");
}

When I run this I am not getting console errors and none of the console.log calls are displaying anything. The player variable stays undefined.

The iframe produced by AMP does have "enablejsapi=1" in the URL.

Do I need to do anything/am I missing something, to get the pause event on the video?

thairish
  • 983
  • 2
  • 10
  • 16
  • What call to the function onYouTubeIframeAPIReady? – The scion Jun 29 '16 at 19:17
  • The code I'm trying comes from a fiddle I found, I haven't used the API before so just trying to get a basic example working: http://jsfiddle.net/bf7zQ/2/ – thairish Jun 29 '16 at 19:22
  • Found a solution from the answers here: http://stackoverflow.com/questions/12256382/youtube-iframe-api-not-triggering-onyoutubeiframeapiready and got the pause event thanks to Hakan's answer – thairish Jun 29 '16 at 23:26

1 Answers1

1

You need to have a parameter on function onPlayerStateChange to get the event data.

function onPlayerStateChange(event) {
    switch(event.data){
        case 2:
            console.log("PAUSE!")
            break;
    }
}

other event.data list

  • -1 (unstarted)
  • 0 (ended)
  • 1 (playing)
  • 2 (paused)
  • 3 (buffering)
  • 5 (video cued).
Hakan Kose
  • 1,649
  • 9
  • 16