Reputation: 195
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&controls=0&showinfo=0&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!
Upvotes: 2
Views: 5303
Reputation: 184
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.
Upvotes: 2
Reputation: 307
Maybe I don't understand your question. Because I tried your code and it works. I can see a page with a youtube video. On clicking play button the video starts and when I click again on the video in pauses. So what is your problem. I'm sorry if I don't use comments but I can't yet.
Upvotes: 0