JavaScript play / pause button for YouTube iframe

advertisements

I'm working on a website, and i'm trying to get an youtube video in an <iframe> tag to play and pause with one button. I can get it to play or pause with separate buttons, but I can't seem to get the if statement to work in order to control the video with just one button. I'm still relatively new to JavaScript, so it may just bee something simple I missed, but I'v searched online for a while now, and could not find anything that solved my problem.

Below is the code I use right now. The first time I click the button the YouTube video play's, but the second time nothing happens. I also tried turning autoplay on for the embedded video, but then when I press the button, nothing happens at all.

This is the code I'm currently using:

HTML

<div class="iframe">
  <iframe id="iframe1" width="360" height="203" src="https://www.youtube-nocookie.com/embed/videoseries?list=PLb-Mg8r29XuOV9CbkXVDQ5NdQG__WbJqI&amp;controls=0&amp;showinfo=0&amp;enablejsapi=1" frameborder="0" allowfullscreen></iframe>
  <a href="#" onclick="iframe1play();return false;">
    <div id="iframe1play">
    </div>
  </a>
</div>

JavaScript

function onYouTubePlayerAPIReady() {
    iframe1 = new YT.Player('iframe1');
} 

function iframe1play() {
    if (event.data == YT.PlayerState.PLAYING && !done) {
        iframe1.pauseVideo();
        document.getElementById("iframe1").style.opacity = "0";
    } else {
        iframe1.playVideo();
        document.getElementById("iframe1").style.opacity = "1";
    }
}

var tag = document.createElement('script');
tag.src = "//www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

Any suggestions are appreciated!


Ok so the main problem was that you didn't have event object in your function.

this should do the trick

if (player.getPlayerState() == YT.PlayerState.PLAYING) {
        player.pauseVideo();
        document.getElementById("iframe").style.opacity = "0";
    } else {
        player.playVideo();
        document.getElementById("iframe").style.opacity = "1";
    }

Use jQuery or other framework, if you can,for injecting functions to elements.