Jquery – Check if YouTube video is playing and run script


I have the following video embeded within WordPress

<iframe id="video" width="640" height="360" src="http://www.youtube.com/embed/xxxxxx?enablejsapi=1" frameborder="0" allowfullscreen></iframe>

And it's inside a SlideDeck slider, which I want to stop when someone clicks the video. I can't figure out how to get this line of code

self.pauseAutoPlay = true;

to run when the video is playing.

I desperately need some help please.

Edit: As I'm not the end user. I need something that will work with the default embed code from YouTube.

Best Solution

You need to use the YouTube iFrame API. Keep in mind, I know just the bare basics of Javascript and so on so this could potentially be a lot more efficient.

You them embed your iframe as you normally would

<iframe id="player" width="640" height="360" src="http://www.youtube.com/embed/TJ2X4dFhAC0?enablejsapi" frameborder="0" allowfullscreen></iframe>

But with a couple changes. It needs to have an ID, 'player', and you need to append ?enablejsapi to the end of the source URI.

You'll then need to run the following script to load the API JS as well as creat the player

// 2. This code loads the IFrame Player API code asynchronously.
      var tag = document.createElement('script');
      tag.src = "http://www.youtube.com/player_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player;
  function onYouTubePlayerAPIReady() {
    player = new YT.Player('player', {
      height: '390',
      width: '640',
      videoId: 'u1zgFlCw8Aw',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange

Notice that new YT.Player('player' should match your iframe ID and that videoId: 'u1zgFlCw8Aw' should match the src URI.

After this you'll be able to run scripts like

var myPlayerState;
      function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PLAYING && !done) {
          // DO THIS
        myPlayerState = event.data;

if (myPlayerState == 1){
Related Question