What I want is to have a DIV divided in two, so that when clicking on the left DIV it expands to full height and starts playing the video, while closing it with a close button, the video pauses and the left DIV regains its normal height and width.
I found this code whitch is what im looking, but now I have to add the iframe and make it play and pause in while clicking the play and close button:
[1]: http://jsfiddle.net/davidThomas/CFNUJ/1/
Any ideas?
Thanks!
As explained in the full YouTube player API here, you will want to create an empty div with an id of player for this script to hook into. Once the onPlayerReady event fires, you can hook into the javascript player object that the script creates and use it to manipulate the video player with calls like player.playVideo(). The iframe that replaces your empty div can then be modified like any other DOM element to change the size of the video player.
Note: The script I'm providing is cut down from the original API example so that it doesn't stop after 6 seconds
<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
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
function onPlayerStateChange(){
//Do Nothing for now
}
</script>
Related
Good day,
I know this question has been asked many times. I searched high and low to get it to work but it seems that something has changed that the answers are not working anymore.
On YouTube, when I run this simulateClick function in the console. It works.
function simulateClick() {
var evt = new MouseEvent("click", {
bubbles: true,
cancelable: true,
view: window
});
var cb = document.getElementsByClassName("ytp-play-button")[0]; //element to click on
var canceled = !cb.dispatchEvent(evt);
if(canceled) {
// A handler called preventDefault
alert("canceled");
} else {
// None of the handlers called preventDefault
alert("not canceled");
}
}
That is because there is a button called "ytp-play-button".
However, when I take that to YouTube TV (formerly leanback). It does not work. The div function there has a "role=button".
This is the div responsible for the play button.
<div class="toggle-button selected material-icon-play-arrow toggle-selected transport-controls-toggle-button" tabindex="-1" role="button" style=""> <div class="background"></div> <span class="label">Pause</span></div>
So I changed the "ytp-play-button" to the "material-icon-play-arrow" but even though it gets the class right. It does not work.
Any pointers would be truly appreciated it. Thank you.
P.S.: This is a pure JavaScript question not a jQuery one.
Edit#1: When I tried to run the onclick like this in the console
document.getElementsByClassName("material-icon-play-arrow")[0].onclick()
I got this error.
Uncaught TypeError: document.getElementsByClassName(...)[0].onclick is not a function
at :1:64
(anonymous) # VM7969:1
You can use YouTube Iframe Player API for set a embed YouTube video and control the way you can interact with the video.
For your specific case, you need play/pause a YouTube video by clicking an HTML element (in this case, a div element).
For achieve this functionality, you can use the following code - see the working sample in this jsfiddle.
There, basically I have a div element (called playButton) and (using the onPlayerStateChange function) I set the click event as follows:
When the video is playing, the div playButton will have its text as "Pause" and its click event allows pause the video.
When the video is paused, the div playButton will have its text as "Play" and its click event allows play the video.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Variables of the divs (where the YouTube iframe will load):
var player;
function onYouTubeIframeAPIReady() {
// Div player:
player = new YT.Player('player', {
height: '360',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
// After loading the iframe, set the "playVideo" onclick event on "playButton" anchor element.
document.getElementById('playButton').onclick = function() {
player.playVideo();
};
}
// 5. The API calls this function when the player's state changes.
function onPlayerStateChange(event) {
// If the video is PLAYING, set the onclick element for pause the video.
// Once the "playButton" is clicked, the video will be paused.
if (event.data == YT.PlayerState.PLAYING) {
document.getElementById('playButton').innerHTML = 'Pause';
// Set the onclick event to the button for pause the YouTube video.
document.getElementById('playButton').onclick = function() {
player.pauseVideo();
};
}
// If the video is PAUSED, set the onclick element for pause the video.
// Once the "playButton" is clicked, the video will resume the video = continue playing the video.
if (event.data == YT.PlayerState.PAUSED) {
document.getElementById('playButton').innerHTML = 'Play';
document.getElementById('playButton').onclick = function() {
player.playVideo();
};
}
}
// Div "player" - The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
<!-- In this div, the YouTube video will be loaded with YouTube iframe Player API. -->
<div id="player"></div>
<!-- N.B this is the div element used for play or pause the current video loaded with YouTube iframe Player API. -->
Play
Here is the "Playback controls and player settings" in the official documentation for further details.
Is there an "onload" of the video for an embeded youtube iframe?
I'd like to start my script only after the music video i have selected starts.
I have stuck an onload event onto the iframe the youtube video is delivered in, but that does not correspond to the loading (buffering has finished ready to play) of the actual video. It only corresponds to when the video player has been loaded in the page.
In other words, is there any way to detect with javascript when a youtube video starts playing?
Everything you're looking for can be found in the Youtube Iframe API reference.
I'll paste the relevant code here as well, but be aware that I only modified one line to trigger an alert onReady. The rest of the code comes from the aforementioned reference page.
<!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
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
alert("Video Ready!");
event.target.playVideo(); // You can omit this to prevent the video starting as soon as it loads.
}
// 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>
I have used Youtube API to play automatically a video but i have found out that it only works fine on PCs but NOT mobile devices. I did a bit of google-ing and discovered that autoplay feature is disabled on mobile devices.
No the questions is, can i detect if autoplay is disabled ??. Or at least force the video to show youtoube play button if vidio is on state -1.
i.e.
if(event.data == -1) {
// show play button
}
It appears that there is no way of getting this information without testing with you video and checking whether the video's current time has advanced after it has loaded.
It was asked for as a feature in modernizr but as you can see from this comment from Paul Irish, you have to have a video to check. It looks like they are trying to add this into v3 of modernizr.
So essentially it is doable and his pseudocode should get you started. Basically the first four points are done already. You would just need to implement the last two.
create a video element
set video element src to something
add autoplay attribute to it
add element to the dom
bind to that event (something metadata soemthing) that fires when its buffered some
setTimeout after it fires and see if currentTime is > 0
A sample to autoplay without using arg autoplay. I only test this solution on PCs not mobile but you can try this code :
LIVE EXAMPLE
HTML
<div id="player"></div>
JS
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 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();
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
} else {
}
}
function stopVideo() {
player.stopVideo();
}
I have copied the Youtube embedded player demo code Youtube embedded player demo code almost verbatim - the changes are inserting console.log so that I can see what is going on.
<!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
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
console.log('onPlayerReady');
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) {
console.log('onPlayerStateChange');
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
</body>
</html>
This works as intended in Safari and Firefox, that is once the API loads the choosen video plays for six seconds and the console.log contains evidence that the events are firing. However in Internet Explorer the events onReady and onStateChange do not fire. The video will play if I manually click the play control in the player but I do not get the expected onStateChange events.
I checked the version of Flash on my machine and it is: 11.2.202.228 and the current available is 12.0.0.70. If I disable Flash in IE (manage add ons) the player works as expected: plays for 6 seconds and events fire.
I did not update Flash because while that might fix the issue on my machine my audience will be limited to those only that can do the same and if I updated I would not be able to find out if the issue was resolved by other means.
I have also tried to manually create the iframe myself as mentioned in the above Youtube documentation, this worked as expected in Firefox and Safari but not in IE.
There is a Youtube demo player this works perfectly in Firefox, the play, pause and stop controls via the API work and the events are clearly firing as the Events and Function Calls are written to the screen in the "Statistics" section. In contrast when I look at this in IE the play, pause and stop controls via the API do nothing. There is no output in the statistics section. The only way to play and pause is to use the buttons on the player. If I disable Flash then the player & API works perfectly.
If I try an iframe non API embed then the player works correctly, this leads me to believe that it is an issue arising from using the API.
I know some would say that all users should have the latest Flash, easier said than done. Many schools, companies and libraries lock down the options section in IE so the user would be able to turn off Flash for my site.
I wonder is there some way of turning off Flash when using the API?
I have searched around Stackoverflow and elsewhere and while I have found similar issues I have not found any fixes. I did find a somewhat similar promising lead but alas I had no joy. Also here and here and here and here and here.
I must point out that the issue is present when used on a local machine and on a website and even if I set the origin parameter.
I would appreciate suggestions and help. Thanks in advance.
I wonder is there some way of turning off Flash when using the API?
You could force the YouTube player to use its html5 player using the following option:
playerVars: {html5: 1}
Changing your code to:
// 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',
playerVars: {
html5: 1
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
I want to use the YT.Player code so that I can detect events. I have a CSV file with Youtube video ID's and a function that puts the ID's in an array and want to be able to dynamically change the ID when a user click an image. Essentially like this:
html
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
javascript
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "//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.
// NOTE: videoId is taken out and instead is placed as the generated IFRAME src from the postSelection function
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '100%',
width: '100%',
videoId: '<<CALL TO FUNCTION OR VARIABLE HERE>>',
events: {
//'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
If you are familiar with this code then what happens is the #player DIV is replaced by an IFRAME. I can change the IFRAME source with this function:
function postSelection() {
$("#player").attr("src", _selected.attributes.url); //_selected.attributes.url comes from the CVS file
}
But this is very buggy and not cross browser friendly. If I use a standard IFRAME and not the YT Player API then everything works just fine. But I want to detect the end, and pause and so on so I have to use the API. My guess is that it is an issue with state and that persistence is lost some where in the creation of the IFRAME.
Regards.
This is very simple to do with the js api. When you want to load a new video just call player.loadVideoById(videoId); Details at https://developers.google.com/youtube/iframe_api_reference#loadVideoById
In case this is of help to anyone struggling as I did...
This player.loadVideoById(videoId) was only working for me when videoId was hardcoded e.g.
player.loadVideoById('sdfexxdfse')
When I tried to put that value into a variable directly or when storing in an array it wasn't working even though it contained the same information.
The video was coming up with incorrect parameter each time.
Adding it to a variable in this way
var x = new String(variabledatahere)
did the job.