Reputation: 2316
Hello :) I want to dim the background of my (wordpress)site as soon as the youtube video starts playing.
The video is embedded like this:
<iframe frameborder="0" width="660" height="371" allowfullscreen="" src="https://www.youtube.com/embed/CMm6tDavSXg?feature=oembed">
To dim the background I would use something like this:
<div class="div_popup_overlay"></div>
.div_popup_overlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #333;
opacity: .7;
z-index: 3000;
}
and then trigger it with jQuery
$( "#YOUTUBEVIDEO" ).click(function() {
$(".div_popup_overlay").fadeIn();
});
// more something like onvideoplay $(".div_popup_overlay").fadeIn();
So now I just can't figure out how to use the youtube api in the right way without embedding the video with the api
Upvotes: 0
Views: 1195
Reputation: 13667
Try this:
First of all, give your iframe an ID, so that the API can find it. Next, make sure that, in the src attribute you append the parameter enablejsapi and set it to 1 (so the API can hook into the existing DOM object's events). Then, set up a binding to the playerState event, so that when the video is playing, it triggers the fade in. Something like this (assuming you've given your iframe the ID of "myplayer"):
<script>
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('myplayer', {
events: {
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
$(".div_popup_overlay").fadeIn();
}
else if (event.data == YT.PlayerState.PAUSED || event.data == YT.PlayerState.ENDED) {
$(".div_popup_overlay").fadeOut();
}
}
</script>
Upvotes: 3