Fade in and Out Youtube Video with JavaScript API - javascript

I am trying to fade in an iframe containing a YouTube video when the video starts, and fade it out when it ends (before it shows the still image with the red player button in the middle). Right now, the video is stuck at opacity: 0. It's like the code isn't detecting the start of the video. Here is my code (most of it is from Google):
HTML
<iframe id="player"
width="560" height="315"
src="https://www.youtube.com/embed/-K2fShrbvfY?modestbranding=1&rel=0&controls=0&enablejsapi"
frameborder="0" allowfullscreen
></iframe>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_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 onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.style.opacity = 1;
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
event.target.style.opacity = 0;
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
CSS
#player{
opacity: 0;
transition: all 1s;
}
I also tried document.getElementById('player').style.opacity = 1; instead of event.target.style.opacity = 1; , but it still does not fade the video in.
New code, thanks to help from below. However, I still get the YouTube water mark and the still image at the end.
<!DOCTYPE html>
<html>
<head>
<style>
#player {
display: none;
}
</style>
</head>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="http://www.youtube.com/player_api"></script>
<script>
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: '0Bmhjf0rKe8',
playerVars: {
modestbranding: 1,
rel: 0,
controls: 0,
showinfo: 0
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
$('#player').fadeIn(function() {
event.target.playVideo();
});
}
// when video ends
function onPlayerStateChange(event) {
if (event.data === 0) {
$('#player').fadeOut();
}
}
</script>
</body>
</html>

Try this
<!DOCTYPE html>
<html>
<head>
<style>
#player {
display: none;
}
</style>
</head>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="http://www.youtube.com/player_api"></script>
<script>
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: '0Bmhjf0rKe8',
playerVars: {
modestbranding: 1
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
$('#player').fadeIn(function() {
event.target.playVideo();
});
}
// when video ends
function onPlayerStateChange(event) {
if (event.data === 0) {
$('#player').fadeOut();
}
}
</script>
</body>
</html>
However
You cannot remove the watermark
Reference YouTube API
modestbranding:
This parameter lets you use a YouTube player that does not show a YouTube logo. Set the parameter value to 1 to prevent the YouTube logo from displaying in the control bar. Note that a small YouTube text label will still display in the upper-right corner of a paused video when the user's mouse pointer hovers over the player.

Related

Javascript - How to change src of iframe when video ends

I would like to know how can I change the source of iframe automatically when video ends.
I am using this script to generate iframe and the function onPlayerStateChange to detect when the video ends. I basically need to change the videoID after the video finishes playing.
My JS:
<script src="http://www.youtube.com/player_api"></script>
<script>
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
width: '640',
height: '390',
videoId: 'gPDcwjJ8pLg',
events: {
onStateChange: onPlayerStateChange
}
});
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
}
}
</script>
Thank you for any advice.
If you want to do this for several videos, you will need to generalize this. But I think this example (of an index.html file) should work:
<div id="player"></div>
<script src="http://www.youtube.com/player_api"></script>
<script>
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: '0Bmhjf0rKe8',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
event.target.playVideo();
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
player.loadVideoById('iRXJXaLV0n4');
}
}
</script>
Here is the jsFiddle: http://jsfiddle.net/lukeschlangen/dbrhgdkb/1/

YouTube Iframe API - Play video on mobile

After searching and finding many similar questions, I can't find the correct answer. So I'm working with the YouTube Iframe API, and I know that autoplay etc. won't work for mobiles. And I have created a element that displays on mobiles, so when the user click that button, it should play the video. But I only get this message: "Try restarting your device if playback does not start soon".
var playElement = document.createElement("div");
playElement.style.display = "none";
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
playElement.style.display = "block";
}
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player(child, {
width: '100%',
height: '100%',
videoId: youtubeID,
playerVars: {
'iv_load_policy': 3,
'enablejsapi': 1,
'disablekb': 1,
'autoplay': 1,
'loop': 0,
'controls': 0,
'showinfo': 0,
'rel': 0,
'mode': 'transparent'
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
playElement.onclick = function() {
player.playVideo();;
};
Anyone that does have an actual working solution?
Remember player refers to a div with the ID 'player'. You can start with the example code on youtube api doc. It will autoplay when the video has loaded. You can add your playerVar options as well.
A note for mobile video autoplay. You can have it autoplay but it has to be muted. So you can try adding player.mute() when you it loads and setup a click handler to unmute it again if that is what you prefer.
<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_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 onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
},
playerVars
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
</body>
</html>

Make YouTube api automatically start another video when first video ended

I need to make a video page for my website which must contain a video from youtube (https://www.youtube.com/watch?v=bWPMSSsVdPk) and after this video ended I need to automatically display a second video (https://www.youtube.com/watch?v=0afZj1G0BIE) and the div with class content
This is my code so far:
<style>
.content {
display: none;
}
</style>
<div class="content">
<button>Show this button after first video ends</button>
</div>
<div id="player"></div>
<script src="http://www.youtube.com/player_api"></script>
<script>
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'bWPMSSsVdPk',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
event.target.playVideo();
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
alert('done');
}
}
</script>
I've found a solution for this but it seems that the sound of the second video is also playing in the same time with the first video...
<style>
.second-video {
display: none;
}
</style>
<div class="video-site">
<div class="first-video">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<div id="player"></div>
</div>
<div class="second-video">
<div id="player2"></div>
</div>
</div>
<script src="http://www.youtube.com/player_api"></script>
<script>
// create youtube player
var player;
var player2;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'qCDxEif_9js',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
player2 = new YT.Player('player2', {
height: '390',
width: '640',
videoId: '43jHG-yH9Gc',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
event.target.playVideo();
$('.close').click(function(){
$('.first-video').hide(3000);
$('.second-video').fadeIn();
});
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
$('.first-video').hide(3000);
$('.second-video').fadeIn();
}
}
</script>
There is no direct way as to how one can do this with the available set of parameters that a Youtube iframe Player API has. But you can try doing this.
Create a Playlist of the video's you want to play consecutively in the same order.
In the REST API call set the listType parameter as playlist.
Retrieve the playlistID of that particular playlist.
http://www.youtube.com/embed?listType=playlist&list=PLPLAYLISTID
Finally, set the autoplay parameter to 1 so that the video's in the playlist play automatically.
function onPlayerStateChange(event) {
if(event.data === 0) {
event.target.loadVideoById("0afZj1G0BIE");
}
}
That'll play your next video right after your first. However that also calls playVideo() which will be an issue for anyone watching on an Apple mobile device. Consider using cueVideoById() instead.

setPlaybackQuality not working YouTube JS API

First video is loaded in 1080p than when I press a button with class="quality" It should change the quality to 720p but it's not working in HTML5 player.
It works on Flash Player but not in HTML5. I'm using JavaScript Player API.
Note: None of these solutions worked for me. YouTube iFrame API "setPlaybackQuality" or "suggestedQuality" not working
function onPlayerReady(event) {
event.target.playVideo();
event.target.setPlaybackQuality('hd1080'); //works
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
$(".quality").click(function() {
event.target.setPlaybackQuality('hd720'); //doesn't work
});
}
}
The problem is you can not downgrade quality. Once you set to 1080p for ex you can not go back to 720p.
I have taken the example from this site YouTube Player API Reference for iframe Embeds.
I have manually added one button to change the quality which is working absolutely fine, Here is the working code.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<button id="change_quality">Change Quality</button>
<div id="player"></div>
<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('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
event.target.setPlaybackQuality('360p');
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
$("#change_quality").click(function() {
event.target.setPlaybackQuality('240p');
});
}
}
</script>
</body>
</html>
Initially onPlayerReady the quality is set to 360p.
After clicking on Change Quality button the quality is set to 144p.
Try stopping the video, then setting the playback quality, then resuming playback.
function onPlayerStateChange(event) {
$(".quality").click(function() {
event.target.stopVideo();
event.target.setPlaybackQuality('hd720');
event.target.playVideo();
});
}

YouTube API OnStateChange Listener Stops Working After Switch SRC Attr

I am trying to change the video playing in the YouTube iframe in the cleanest way possible and a few months ago I had this code working, but YouTube changed their API and it stopped working for me. Now the onPlayerStateChange event is not firing after I switch out the video's SRC attribute to switch the video that is playing. I'm an amateur to coding so I may be missing something simple here, but any input would be greatly appreciated.
Below is a code that loads a YouTube video and when it ends, there's an alert that automatically pops up for you. However, when you click the button and switch the video by switching out the SRC attribute, the alert function stops working and its as if the entire onPlayerStateChange function stops working. I could not get it working in jsfiddle, but a link to a live demo can be found at http://thetunedrop.com/test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<div id="player"></div>
<button class="button" data-youtubeid="b-3BI9AspYc">BUTTON</button>
</body>
</html>
<script type="text/javascript" src="jquery/jquery.min.js"></script>
<script type="text/javascript" src="jquery/js/jquery-ui-1.8.22.custom.min.js"></script>
<script src="http://www.youtube.com/player_api"></script>
<script>
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: '0Bmhjf0rKe8',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
event.target.playVideo();
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
alert('done');
}
}
function load_ytid(youtubeid){
$("#player").attr("src", "http://www.youtube.com/embed/" + youtubeid + "?fs=1&autoplay=1");
}
$(document).ready(function(){
$(".button").on("click", function(){
var youtubeid = $(this).data("youtubeid");
load_ytid(youtubeid);
});
});
</script>
Try this instead :
<!DOCTYPE html>
<html>
<body>
<script src="jquery-1.10.2.min.js"></script>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<button class="button" data-youtubeid="b-3BI9AspYc">BUTTON</button>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_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 onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: '0Bmhjf0rKe8',
playerVars: { 'autoplay': 1, 'controls': 1 },
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
var playerReady = false;
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
playerReady = true;
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED ) {
alert('done');
}
}
$(".button").on("click", function(){
player.loadVideoById("Vw4KVoEVcr0", 0, "default");
});
</script>
</body>
</html>
The fiddle here : http://jsfiddle.net/QtBlueWaffle/8bpQ8/1/
Hope this helps
I had kind of the same problem (I Think)... I wanted the user to be able to change the content for multiple players, and this is what works for me: I call the youtube api with a onload function additional to the new Youtubelink, so that reloads every time the iframe changes.
MY HTML:
<iframe onload="floaded1()" id="player1" width="240" height="220"
src="http://www.youtube.com/embed/0Bmhjf0rKe8
?enablejsapi=1&rel=0&showinfo=2&iv_load_policy=3&modestbranding=1"
frameborder="0" allowfullscreen> </iframe>
MY JS:
function floaded1() {
player1 = new YT.Player('player1', {
events: {
'onStateChange': function (event) {
if (event.data == 0) {
alert('done');
};
}
}
});
}
WHAT I LOAD WITH A VIDEO PICKER:
html += '<iframe onload="floaded1()" id="player1" width="240" height="220"
src="http://www.youtube.com/embed/'+YouTubeVideoId+'?enablejsapi=1&rel=0&
showinfo=2&iv_load_policy=3&modestbranding=1" frameborder="0" allowfullscreen>
</iframe>';

Categories

Resources