I'm currently working with the youtube iframe API.
var player,
time_update_interval = 0;
function onYouTubeIframeAPIReady() {
player = new YT.Player('video-placeholder', {
width: 600,
height: 400,
videoId: 'Xa0Q0J5tOP0',
playerVars: {
color: 'white',
playlist: 'taJ60kskkns,FG0fTKAqZ5g'
},
events: {
onReady: initialize
}
});
}
function initialize(){
// Update the controls on load
updateTimerDisplay();
updateProgressBar();
// Clear any old interval.
clearInterval(time_update_interval);
// Start interval to update elapsed time display and
// the elapsed part of the progress bar every second.
time_update_interval = setInterval(function () {
updateTimerDisplay();
updateProgressBar();
}, 1000);
$('#volume-input').val(Math.round(player.getVolume()));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.youtube.com/iframe_api"></script>
...<br>
<div id="video-placeholder"></div>
<br>...
So far it all works great but I want to display the latest video of a specific channel. I know it's something with user_feed but I don't know how exactly to do it as I'm a complete js/api beginner.
Thanks
Related
if I use this
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('video-placeholder', {
width: 600,
height: 400,
videoId: 'zYdquUPcRSw',
playerVars: {
color: 'white',
},
});
}
function myFunction() {
console.log(player);
player.playVideo();
}
it works, but I want youtube show when scroll event is triggered, so I add line code like this,
var player;
function onYouTubeIframeAPIReady() {
window.onscroll = function() {
player = new YT.Player('video-placeholder', {
width: 600,
height: 400,
videoId: 'zYdquUPcRSw',
playerVars: {
color: 'white',
},
});
}
}
function myFunction() {
console.log(player);
player.playVideo();
}
It works, youtube show just when I scroll the window, but function playVideo() don't work (note: playVideo() there is inside myFunction()). after I try to show player variable with console.log(player). I see that there is no function inside the variable like this :
different result when I dont use window.onscroll function, if I use console.log to variable player, the result is this :
is it possible to do it "show and make own control youtube with youtubeIframeAPI and triggered by scroll event" ?
I'm stuck on a piece of JavaScript code that applies an event on the Youtube API. The goal is when you click on the appropriate button, the video moves backwards by 5s, 10s or 30s or advances by 5s, 10s or 30s.
My problem is that I have six functions that are alike but do not have the same time values. (in this example I put only two of the functions: rewind5() to back up 5 seconds and rewind10() to back up 10 seconds).
I am looking for a charitable soul that could help me to combine these two functions (rewind5() and rewind10()) into a single function. Once I have the right structure I could create the four other functions using the single function.
My JS file :
// Rewind 5s
function onPlayerReady(event){
if(player.getPlayerState()===1 || player.getPlayerState()===2){
$('#s5back').prop('disabled', false);
$( '#s5back' ).click(function() {
rewind5();
});
} else {
$('#s5back').prop('disabled', true);
}
}
function rewind5() {
var currentTime = player.getCurrentTime();
player.seekTo(currentTime - 5, true);
player.playVideo();
};
// Rewind 10s
function onPlayerReady(event){
if(player.getPlayerState()===1 || player.getPlayerState()===2){
$('#s10back').prop('disabled', false);
$( '#s10back' ).click(function() {
rewind10();
});
} else {
$('#s10back').prop('disabled', true);
}
}
function rewind10(){
var currentTime = player.getCurrentTime();
player.seekTo(currentTime - 10, true);
player.playVideo();
};
My HTML file :
<div id="video-placeholder"></div>
<script type="text/javascript">
var player,
time_update_interval = 0;
function onYouTubeIframeAPIReady() {
player = new YT.Player('video-placeholder', {
width: '100%',
height: '625px',
videoId: 'ID URL YOUTUBE',
playerVars: {
color: 'white',
controls: 0,
rel: 0,
showinfo: 0
},
events: {
onReady: initialize,
onStateChange: onPlayerReady
}
});
}
</script>
Why not have just a single seekBy function, and pass it the desired number of seconds to rewind?
function seekBy(secs){
var currentTime = player.getCurrentTime();
player.seekTo(currentTime + secs, true);
player.playVideo();
}
and implement it with, for example
$('#s10back').click(function() {
seekBy(-10);
});
or 5 seconds, or 30, or 60. To go forward, pass a positive number instead:
$('#s10forward').click(function() {
seekBy(10);
});
I'm having an issue with the following code, but I'm not sure where the problem is.
On my master page, in javascript, I have an array defined to hold a list of YouTubePlayer objects that I create. I also load the YouTube API here.
I also have (sometime several) YouTube user control(s) that contains the YouTube div in a bootstrap modal. It also contains a JavaScript for pushing a new YouTubePlayer object to the array in the master page js. Lastly, on the user control, I define methods for auto-starting and stopping the video on the 'shown' and 'hide' events of the bootstrap modal.
Finally, to (hopefully) solve the race condition between the document being loaded and the YouTube API being loaded, I set two bool variables (one for document, one for API), and check both for true before calling an initVideos function which iterates through the array of YouTubePlayer objects and initializes them, setting the YT.Player object in the window. Part of the issue, I think, is that I can't statically set window.player1 etc., because I never know how many YouTube user controls will be loaded.
The problem is whenever the bootstrap modal events fire, the YT.Player object I retrieve from the window doesn't contain the methods for playVideo() and pauseVideo().
On my master page:
$(document).ready(function () {
window.docReady = true;
if (window.apiReady)
initVideos();
});
function onYouTubeIframeAPIReady() {
window.apiReady = true;
if (window.docReady)
initVideos();
initVideos();
}
function initVideos() {
if (typeof ytPlayerList === 'undefined')
return;
for (var i = 0; i < ytPlayerList.length; i++) {
var player = ytPlayerList[i];
var pl = new YT.Player(player.DivId, {
playerVars: {
'autoplay': '0',
'controls': '1',
'autohide': '2',
'modestbranding': '1',
'playsinline': '1',
'rel': '0',
'wmode': 'opaque'
},
videoId: player.VideoId,
events: {
'onStateChange': player.StateChangeHandler
}
});
window[player.Id] = pl;
}
}
And on the user control:
window.ytPlayerList.push({
Id: "<%=ClientID%>player",
DivId: "<%=ClientID%>player",
VideoId: "<%=VideoId%>",
StateChangeHandler: hide<%=ClientID%>Player
});
function hide<%=ClientID %>Player(state) {
if (state.data == '0') {
hide<%=ClientID %>Video();
}
}
function show<%=ClientID %>Video() {
$('#<%=ClientID %>video-modal').modal('show');
}
function hide<%=ClientID %>Video() {
$('#<%=ClientID %>video-modal').modal('hide');
}
$(document).ready(function() {
$("#<%=ClientID%>Video").click(function() {
show<%=ClientID%>Video();
});
$("#<%=ClientID %>video-modal").on('shown', function () {
window["<%=ClientID%>player"].playVideo();
});
$("#<%=ClientID %>video-modal").on('hide', function () {
window["<%=ClientID%>player"].pauseVideo();
});
});
This may be a lack of js expertise, but I'm absolutely stuck. Any help would be greatly appreciated. Also, for reference, the exception I get is
Uncaught TypeError: window.ctl100_phContent_ctl100player.playVideo is not a function
So the problem is that the video only gets that playVideo() method when the YouTube API has finished loading the video element. This video element is loaded async, so the code execution will continue with the $(document).ready(function() { jQuery code where it will try to attach the playVideo() functions which at that point in time - do not yet exist.
I've reproduced this error in that HTML/JS page:
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title></title>
</head>
<body>
<div id="ctl100_phContent_ctl100player" style="border:1px solid red;"></div>
<div id="ctl100_phContent_ctl101player" style="border:1px solid red;"></div>
<div id="ctl100_phContent_ctl102player" style="border:1px solid red;"></div>
<script src="https://www.youtube.com/iframe_api"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.6.2.min.js"><\/script>')</script>
<script>
window.ytPlayerList = [];
window.players = [];
window.ytPlayerList.push({ Id: 'ctl100_phContent_ctl100player', DivId: 'ctl100_phContent_ctl100player', VideoId: 'IaHxPi9dM7o', StateChangeHandler: 'hide_player_1' });
window.ytPlayerList.push({ Id: 'ctl100_phContent_ctl101player', DivId: 'ctl100_phContent_ctl101player', VideoId: 'IaHxPi9dM7o', StateChangeHandler: 'hide_player_2' });
window.ytPlayerList.push({ Id: 'ctl100_phContent_ctl102player', DivId: 'ctl100_phContent_ctl102player', VideoId: 'IaHxPi9dM7o', StateChangeHandler: 'hide_player_3' });
function onYouTubeIframeAPIReady() {
initVideos();
}
function initVideos() {
for (var i = 0; i < ytPlayerList.length; i++) {
var player = ytPlayerList[i];
var pl = new YT.Player(player.DivId, {
height: '390',
width: '640',
videoId: player.VideoId,
});
window[player.Id] = pl;
}
}
window.ctl100_phContent_ctl100player.playVideo();
</script>
</body>
</html>
This gives me the same error you describe. So in order to test my theory ( and make sure there were no other script errors ) I did this:
setTimeout(function() {
window.ctl100_phContent_ctl100player.playVideo()
}, 1000);
That did work. So indeed this seems to the problem. However - we don't know for sure that 1000ms is enough to guarantee that the player is initialized. So what you could do - if you want to not refactor too much - is start listening for the onready events of the player:
function initVideos() {
for (var i = 0; i < ytPlayerList.length; i++) {
var player = ytPlayerList[i];
var pl = new YT.Player(player.DivId, {
height: '390',
width: '640',
videoId: player.VideoId,
events: {
'onReady': window[player.Id + '_ready']
}
});
window[player.Id] = pl;
}
}
Which assumes you used codegeneration to create functions like:
function ctl100_phContent_ctl100player_ready() {
// Hook up the hide() / onShow() and other behaviors here
// ... to prove that playVideo() is a function here, I'm calling it
window.ctl100_phContent_ctl100player.playVideo();
}
function ctl100_phContent_ctl101player_ready() {
window.ctl100_phContent_ctl101player.playVideo();
}
function ctl100_phContent_ctl102player_ready() {
window.ctl100_phContent_ctl102player.playVideo();
}
So this is not a copy-paste solution for you problem but should give you insight into why the code is not working. There are probably more elegant ways to achieve what you're trying to do, but let's just keep the fix simple for now.
Let me know if it worked or if you have any other questions.
Youtube allows embedding user created playlist with the help of iframe code. I would like to embed them in a webpage to be played back on Android (Kitkat 4.4) tv box hardware. However it requires user to first click on the video.
As I found out that Apple iOS and Android disables autoplay on most mobile platforms to avoid poor user experiences
However, is it possible to simulate a user click on the iframe using Jquery or pure JS solution (preferred). Something like this:
function myFunction() {
setTimeout(function() { ("#myiframe").triggerHandler('click'); },3000)
};
I'd be very grateful if somebody can help me with this as this functionality is crucial for my purpose and I have searched extensively but couldn't get a proper solution.
thanks
dkj
Good morning dkjain,
as far as I've read in the Youtube Player API docs, there are several events triggered as soon as the Player is loaded, one of these events that should be used is the onReady() event.
Here's some updated code on how to auto-play a single video or a playlist:
HTML:
<div id="player"/>
will be the placeholder for the Youtube player
Playing a playlist (with playerVars):
JS:
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
playerVars: {
'listType': 'playlist',
'list': 'PLi5VEqNXXQjVJ4-xZb92wTUawkSQRal0u'
},
events: {
'onReady': onPlayerReady
}
});
}
window.onYouTubeIframeAPIReady = onYouTubeIframeAPIReady;
// as soon as the player is loaded, start the playback
function onPlayerReady(event) {
event.target.playVideo();
}
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/iframe_api";
document.head.appendChild(tag);
There is also an autoPlay: 1 playerVar, but this does not seem to be available on mobile plaforms: https://developers.google.com/youtube/iframe_api_reference#Mobile_considerations
Play a single video
JS:
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'nhX4rQ79C1A',
events: {
'onReady': onPlayerReady
}
});
}
window.onYouTubeIframeAPIReady = onYouTubeIframeAPIReady;
// as soon as the player is loaded, start the playback
function onPlayerReady(event) {
event.target.playVideo();
}
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/iframe_api";
document.head.appendChild(tag);
JSFiddles showing the above code:
Single video: http://jsfiddle.net/Moonbird_IT/akjpmvpf/
Playlist: http://jsfiddle.net/Moonbird_IT/akjpmvpf/4/ (updated again)
Let me know if we are going in the right direction :-)
So I'm writing a TamperMonkey script that sends specific videos to YouTube's embedded player however I want to automatically send them back once the video is finished.
So for example, video http://youtube.com/watch?v=XXXXX it would redirect to http://youtube.com/v/XXXXX. And then, once the video is complete, it would use window.history.go(-2) (as -1 would go to the normal page causing a loop).
The problem I'm having is that I haven't been able to get the second part, the function that runs when the video finishes, to work.
I have tried following the api and looking at other peoples problems and seeing what helped them but I can't seem to get it.
At the moment this is the code I have.
$(document).ready( function() {
var loc = document.location.href;
var l = loc.split('/');
var s = l[4];
var id = s.split('?')[0]
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
height: '100%',
width: '100%',
videoId: id,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
event.target.playVideo();
alert('spotted');
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
window.history.go(-2);
}
}
});
I would appreciate it if someone would work with me to get this script working.
Thanks.