I was looking for a solution on how to handle key events when running Youtube videos on my application using Youtube iframe API. unfortunately couldn't find any. Did went through this documentation https://developers.google.com/youtube/iframe_api_reference#Events but it seems player doesn't fire any event related to key ( ex: onkeydown, keypress, keyup ).
I tried adding events directly to the provided code but it didnt worked.
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('trailer_video', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
// 'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange,
'onkeydown': myfunction // custom event
}
});
}
Is there any way I can handle key events specially when Arrow keys are pressed ?.
P.S: I dont know I might be wrong here but usually when i press Arrow keys while video is buffering, i see chain of dots moving which gives me a hint, that the player does detects these events and responds.
UPDATE QUESTION
As answer below suggests which is ofcourse a solution in a way but since Youtube also handles left and right arrow key events its possible to use when cursor is over the video as well, My concern is, how can i handle the events for up and down arrow key which are not getting handled by Youtube and which only works when cursor is not over the video if I implement a custom event handler.
It depends on what you are trying to accomplish. But the answer to your question, "Is there any way I can handle key events specially when Arrow keys are pressed?" is yes. Here is an example of a custom rewind/fast-forward functionality that uses the left and right arrow keys:
https://jsfiddle.net/xoewzhcy/3/
<div id="video"></div>
function embedYouTubeVideo() {
player = new YT.Player('video', {
videoId: 'M7lc1UVf-VE'
});
}
function rewind() {
var currentTime = player.getCurrentTime();
player.seekTo(currentTime - 30, true);
player.playVideo();
}
function fastforward() {
var currentTime = player.getCurrentTime();
player.seekTo(currentTime + 30, true);
player.playVideo();
}
$(function(){
// embed the video
embedYouTubeVideo();
// bind events to the arrow keys
$(document).keydown(function(e) {
switch(e.which) {
case 37: // left (rewind)
rewind();
break;
case 39: // right (fast-forward)
fastforward();
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
});
NOTE: Watch out for when you're focused on the embedded video (i.e., you click the YouTube play button or click into the YouTube iframe in any way). Because, your key events won't be listened to since the YouTube iframe is a completely separate window. To get around this, you could overlay a transparent div on the YouTube iframe and build your own play/pause buttons. That way no one can ever click into the iframe and lose focus of the parent window.
I hope this helps!
Related
I'm trying to use the souncloud javascript api to trigger an onplay and onpause call back of an oembeded widget. So basically I'm using SC.oembed to create/display the widget in a div, and then i thought to use SC.stream to control the soundmanager 2 options, but this doesn't seem possible.
All I want to do is call a function when someone presses play on the widget, and when someone presses pause.
What is the best way to achieve this result?
UPDATE
Here's a code snippet
//set up soundcloud gallery
SC.initialize({
client_id: 'MY_CLIENT_ID'
});
SC.get('/users/MY_USER/tracks', function(tracks) {
$('#tracks_holder').addClass('scrollY').empty()
for (var i = 0; i < tracks.length; i++) {
console.log(tracks[i].title);
var newTrack = $('<div class="scTrack"></div>')[0];
SC.oEmbed(tracks[i].permalink_url, {maxheight:"200px"}, newTrack);
$('#tracks_holder').append(newTrack);
}
});
Thanks!
There is a great example HERE. SC allows you to attach handlers to many events, as is in the docs HERE
(function(){
var widgetIframe = document.getElementById('sc-widget'),
widget = SC.Widget(widgetIframe);
widget.bind(SC.Widget.Events.READY, function() {
widget.bind(SC.Widget.Events.PLAY, function() {
// get information about currently playing sound
widget.getCurrentSound(function(currentSound) {
console.log('sound ' + currentSound.get('') + 'began to play');
});
});
// get current level of volume
widget.getVolume(function(volume) {
console.log('current volume value is ' + volume);
});
// set new volume level
widget.setVolume(50);
// get the value of the current position
});
}());
Audio related events:
SC.Widget.Events.LOAD_PROGRESS — fired periodically while the sound is loading.
SC.Widget.Events.PLAY_PROGRESS — fired periodically while the sound is playing.
SC.Widget.Events.PLAY — fired when the sound begins to play.
SC.Widget.Events.PAUSE — fired when the sound pauses.
SC.Widget.Events.FINISH — fired when the sound finishes.
SC.Widget.Events.SEEK — fired when the user seeks.
I'm creating this webpage on wordpress which have videos from youtube in some of it's posts, for tagging purposes I need to capture everytime a person clicks play on each of the videos. I've looked through the web, but all I could find is that, since this videos are on iframes from outside the main domain, it's impossible to catch something from the inside of it, like clicks.
Is there any way that I can catch this clicks on the play button without changing anything on the site? Just from JS.
Regards and thanks in advance.
You could capture some events within the iframe using youtube's js API
This is what you have to do:
1). Load the Player API in your page
<script src="http://www.youtube.com/player_api"></script>
2). Enable jsapi in your iframe as a trailing parameter (enablejsapi) like
<iframe id="myIframe" src="http://www.youtube.com/embed/opj24KnzrWo?enablejsapi=1&autoplay=0" width="420" height="280" frameborder="0"></iframe>
... also notice we added an ID to the iframe.
3). Create 3 functions :
a). onPlayerReady :
Here is where you can detect when the video has loaded and is ready to play. Here you can actually start the video, etc.
function onPlayerReady(event) {
// video is ready, do something
event.target.playVideo();
}
b). onPlayerStateChange :
Here is where you can detect what events are triggered:
function onPlayerStateChange(event) {
console.log(event.data); // event triggered
// e.g. end of video
if (event.data === 0) {
// end of video: do something here
}
}
When you click play or pause, an event is triggered. Then you can decide what action you want do, including pushing a tracking event, etc.
This is a list of the returned values of each event :
-1 – unstarted
0 – ended
1 – playing
2 – paused
3 – buffering
5 – video cued
Refer to the documentation to learn more about those events
c). onYouTubePlayerAPIReady :
This is where you actually initialize the API and bind the events to the other functions :
function onYouTubePlayerAPIReady() {
var id = document.getElementById("myIframe").getAttribute("id");
var player = new YT.Player(id, {
events: {
onReady: onPlayerReady,
onStateChange: onPlayerStateChange
}
});
} // youtube API ready
See JSFIDDLE
I am working on a small project that envolves geting the time to wich a user skips to when playing a video.
I am using the javascript part of the API to play the video, pause and so on, but I cannot seem to understand how to get the time that the user skips to. I know I can seekTo on my own... But there seems to be no corresponding event for when the user does this
I am trying to find the event that fires when the user skips to a certain time...
From YT API I see they do not have such an event (in javascript... I wouldn't like to create my own custom player based on HTML5 and/or AS3).
It seems that there isn't a real way to do it, but probably you can "intercept" it and understand it, it won't take long:
In this page you can see all the featurea available for the api. You can do it in 2 way:
checking and confronting the time of the video with a counter continuously (probably a bad idea).
Intercepting the player state:
There are 5 state for the player, when the player cursor is moved:
-if the player was playing, the state go from 1 to 2 and then from 2 to 1.
-if the players was paused, nothing happens to his state.
Considering that you can intercept the player state you can easily get the current time when the player is paused and then, confront it with the current time when the user restart play. In each of the 2 case, you should be able to know if the user moved or not the cursor. I don't know well this api so I don't know if some other state of the player can mean something important for your question. I think this way, if isn't complete, it's a good start from where begin developing your idea.
UPDATE
HERE IS THE CODE EXAMPLE TESTED + JSFIDDLE
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
var doing = -1;
var timenow=0;
var timeold=0;
var flag=0;
// 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();
}
// 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(flag==1){
flag=0;
timenow=timeold;
}else{
if((doing==-1)&&(event['data']==1)){//start play
doing=1;
}
if((doing==1)&&(event['data']==2)){//from play to pause
timeold=player.getCurrentTime();
timeold=timeold;
doing=2;
console.log('go pause at:'+timeold);
}
if((doing==2)&&(event['data']==1)){//from pause to play
timenow=player.getCurrentTime();
console.log('go play at:'+timenow);
if(timenow>timeold){
alert('are you kidding me?! You switched from '+timeold+' to '+timenow+'!');
player.seekTo(timeold);
flag=1;
}else{
timeold=timenow;
}
}
if(event['data']==5 || event['data']<1){//stopped or ended
doing=-1;
timeold=0;
timenew=0;
}
}
}
function stopVideo() {
player.stopVideo();
}
</script>
</body>
</html>
Google changed something last days, so I have strange problem with Youtube embeded as iFrame in mobile safari. When iFrame is hidden (some parent div has set display:none) during page load and later is changed to be visible, Youtube player do not play.
Any solution? I've tried to reload iframe, when it turns to visible state, it works. But it is not comfortable solution…
I am assuming you are using the third party youtube Iframe API to load the youtube player into a div. The code from youtube actually has a race condition in it where if the div is not loaded/ parsed by the browser prior to onYouTubeIframeAPIReady being called, the video load will fail. In firefox it will just hang and for a second and Chrome is smart enough to deal with the problem.
The solution is to make sure that this code. Is run after the container holding the video is parsed.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
And this code...
function onYouTubeIframeAPIReady() {
Has global scope and is called after the script is created.
The way I typically solve this to to create a function 'class' with the tag creator and event listener and create the object in my document.ready function. Then right below the document.ready function I put.
function onYouTubeIframeAPIReady() {
myVideo.apiReady();
}
Where 'myVideo' is the class I have create and apiReady(); contains.
this.apiReady = function () {
player = new YT.Player('player', {
height: '548',
width: '900',
videoId: 'VIDEO234324',
events: {
'onReady': onPlayerReady
}
});
}
I hope this helps.
I have an embedded youtube video with hidden controls:
<iframe id="ytplayer" type="text/html" width="400" height="225"
src="http://www.youtube.com/embed/dMH0bHeiRNg?rel=0&controls=0&showinfo=0
&loop=1&hd=1&modestbranding=1&enablejsapi=1&playerapiid=ytplayer"
frameborder="0" allowfullscreen></iframe>
I can control it with the youtube Javascript API.
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('ytplayer', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
Things like player.playVideo() and so on work perfectly. Now I am looking for a way to make the video play in fullscreen mode with a Javascript call but I couldn't find any method in the API.
Is it even possible (without the controls) and if so - how?
This worked perfect in my case. You can find more details on this link: demo on CodePen
var player, iframe;
var $ = document.querySelector.bind(document);
// init player
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '200',
width: '300',
videoId: 'dQw4w9WgXcQ',
events: {
'onReady': onPlayerReady
}
});
}
// when ready, wait for clicks
function onPlayerReady(event) {
var player = event.target;
iframe = $('#player');
setupListener();
}
function setupListener (){
$('button').addEventListener('click', playFullscreen);
}
function playFullscreen (){
player.playVideo();//won't work on mobile
var requestFullScreen = iframe.requestFullScreen || iframe.mozRequestFullScreen || iframe.webkitRequestFullScreen;
if (requestFullScreen) {
requestFullScreen.bind(iframe)();
}
}
You can use html5 fullscreen api:
node.requestFullScreen();
document.cancelFullScreen();
document.fullScreen; // bool
But note that:
this usually requires vendor specific prefix like mozRequestFullScreen() or webkitRequestFullScreen
requestFullScreen has to be called on user events (like onclick)
in firefox the fullscreen will be black until "Allow" is clicked by user
I've added code to do fullscreen (real full screen, not full window) to my answer on Auto-Full Screen for a Youtube embed.
YouTube don't expose fullscreen in their API, but you can call the native browser requestFullScreen() function from the playerStateChange() event from the YouTube API or make your own custom play button like I have.
Looking at the API reference for the iframe player, I don't think it's possible to set it to fullscreen (with the iframe API alone)- ctrl f didn't find fullscreen, so either it's a secret method hidden inside the API or it doesn't exist. However, as you probably know, you can set the size of the player player.setSize(width:Number, height:Number):Object, then make the window fullscreen.
Maybe have a look at this similar question. It looks as though this might work for you (using the javascript fullscreen api rather than the Youtube API):
Full Screen Option in Chromeless player using Javascript?
You can try setting the iframe dimension to the window dimension through javascript.
Something like this (using jQuery):
$('ytplayer').attr('width', $(window).width());
$('ytplayer').attr('height', $(window).height());
I hope this can help you.