mardi 30 juin 2015

JavaScript play/pause button for YouTube iframe

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="http://ift.tt/1g6Ew0I" 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!

Aucun commentaire:

Enregistrer un commentaire