I'm using a Vimeo video-embed (iFrame embed code from their website) on my website, and I need the video to automatically stop at a specific timestamp (I'll use 6 seconds here) whenever users of my site play the video. The content after the timestamp is unnecessary.
But unlike YouTube, Vimeo doesn't seem to have an easy way to set end times for any video you embed from them. Unfortunately, I do not own the video so I can't edit the footage directly, so I believe a JavaScript solution is the best option.
Here's the aforementioned iFrame embed HTML from Vimeo that I use on my site:
<iframe id="vidz" src="https://player.vimeo.com/video/401649410?h=11d74aa27c&portrait=0" width="450" height="253" frameborder="0" allow="autoplay; fullscreen; picture-in-picture" allowfullscreen=""></iframe>
Upon trying to select elements within the iFrame (like the video itself), my JS selectors don't seem to be working at all, perhaps because the video is from a separate source not hosted on my site?
Here's code I've been working with, but it doesn't appear to be interacting with the iFrame, as I believe I would need to add this eventListener to a video, directly. But I can't select the embeded video via JS either, it seems. So I'm not quite sure how to handle this:
var vid = document.querySelector("#vidz");
vid.addEventListener("timeupdate", function(){
if(t >= 6000)
{
vid.pause();
}
});
I can also provide the HTML to any elements within the iFrame, but again, I'm not sure how I'd be able to interact with those elements.
Any ideas? Any and all help would be deeply appreciated. Cheers.
use Vimeo js file and below is a script you want video will pause after 6 minutes (specific time) (360 means 6 minutes)
<script src="https://player.vimeo.com/api/player.js"></script>
var iframe = document.querySelector('iframe');
var player = new Vimeo.Player(iframe);
function foo() {
player.getCurrentTime().then(function(time) {
console.log('time:', time);
if(time >= 360){
player.pause()
}
});
setTimeout(foo, 1000);
}
player.on('play', function() {
foo();
});
</script>
Related
I have some embed code like:
<iframe id="video1" class="video" src=""//www.dailymotion.com/embed/video/VIDEO_ID?autoPlay=1&wmode=transparent&loop=1&controls=0&showinfo=0&api=1&endscreen-enable=0&mute=1" allowfullscreen="true" frameborder="0" width="560" height="349"></iframe>
I am trying to access this video using Javascript but the Video ID is not known in advance (it must be able to be set within our CMS and be changed by any editor). Also it is possible to have more than one video on the page. Hard-coding the video ID(s) in my .js file is not possible.
Using the Javascript API, I need to write a custom play/pause function (passing in the button object they clicked) and also to detect when the video has ended and re-start it (to imitate looping, which Dailymotion apparently does not support for some reason). But it seems a call to:
DM.Player(document.getElementById(iframeID), { video: VIDEO_ID})
requires the video's ID to be known (I do know the iFrame ID where the video is but apparently that isn't enough to access the player like it is for other video platforms).
I then need to be able to create a function to call play or pause based on whether the user has clicked the play/pause toggle on a specific video. My Javascript knowledge isn't great, but I have been able to do this with other platforms by knowing the iframe ID. The play/pause does work if I hard-code a video ID but only if there is one video on the page and only if I do not try to "loop" the video.
This is a private video, if that matters - we want it to only be viewed on our website and not on Dailymotion.
Pseudo-code greatly appreciated as I find their API documentation a bit incomplete for a newcomer (such as not specifying if parameters are required or optional, and not listing available options like for params and events during DM.Player initialization)
EDIT: Here is how I access the video API with other video hosting services (YouTube, Vimeo, Brightcove, etc)
I build an array of all HTML elements with a certain class name (recall there can be more than one video). Say the class name is ".video" so I build an array of all ".video" on the page and their corresponding HTML id. I then use document.getElementById to populate the array with the players.
Then in the play/pause click function, I can access the video like so:
var player = players[index];
var state = player.getPlayerState();
if (state == 1) {
player.pauseVideo();
}
else {
player.playVideo();
}
This does not work for Dailymotion because the actual DM Video ID (and not the HTML element's ID) must be known in advance. I was wondering if there is a way to access the video via the Javascript API without knowing the video ID?
I don't use DailyMotion API but I knocked up this experiment which might be useful to you.
See if the comments in my example code below help you to understand how to use your own buttons with JS functions and how to handle video "end" event etc.
<!DOCTYPE html>
<html>
<body>
<!-- 1. Load DailyMotion API (Javascript) -->
<script src='https://api.dmcdn.net/all.js'> </script>
<!-- 2. Create container for DM Player instance -->
<div id='player'></div>
<!-- 3. Javascript stuff goes here -->
<script>
//Set VIDEO_ID (retrieve or update from your CMS)
//**example** var VIDEO_ID = get_video_id.php **where PHP returns/echo the text of ID**
var VIDEO_ID = "xwr14q"; //update this via your CMS technique
//Create DM Player instance//
var player = DM.player(document.getElementById('player'), {
video: VIDEO_ID,
width: "100%", height: "100%",
params: { autoplay: false, mute: true }
});
//Handle video ending (seek back to zero time)//
player.addEventListener('end', function (evt) { evt.target.currentTime = 0; evt.target.play() } );
//Control functions for DM Player instance//
function func_Play()
{ player.play(); }
function func_Pause()
{ player.pause(); }
</script>
<p>
<!-- Buttons for play pause -->
<button onclick="func_Play()"> PLAY </button>
<button onclick="func_Pause()"> PAUSE </button>
</p>
</body>
</html>
Also regarding
"...It is possible to have more than one video on the page"
Do some "experience quality" tests. Just be sure your users don't mind multiple looping videos running at once (eg: may slow your page / their browser, or drain their data allowance if on mobile, etc).
To handle multiple videos, I would just put each video player in it's own HTML page (like above shown code) and then in main page just load multiple iframes pointing to each player's HTML.
I integrated Vimeo Video in my site and I used 'background= 1' parameter in query string to remove all the default functionalities but it cause a problem that my Video get muted when it loads and I want to unmute the video on page load.
I am beginner so please Give me some good and simple solution keeping in mind that background = 1 should stay there.
Here is what I tried so far:
<script>
var dynamicContent = getParameterByName('background');
$(document).ready(function() {
if (dynamicContent=='1') {
$('#vi-video-1-container').attr('data-audio-volume', 1);
$("#vi-banner-video").vimeo("setVolume", 1);
}
});
</script>
I have a webpage, and I made a video for it. With HTML5 formats (webm,ogg,mp4) works only the Chrome correctly. When the video is finishing, I can hide the video with JavaScript. I thought I can make with youtube player, (autoplay, hide controls etc) but i can't hide it, when it is finished. I found the "onStateChange function but I can't use it. Any ideas?
<iframe width="840" height="630" src="URLrel=0&showinfo=0;&autoplay=1;controls=0" frameborder="0" allowfullscreen></iframe>
You need to use the YouTube Iframe Player API to check (1) that the video has ended (YT.PlayerState.ENDED) when onPlayerStateChange is invoked, and (2) remove/hide the DOM element that contains the video, i.e. the iframe.
function onPlayerStateChange(event) {
// check if video ended and remove player
if (event.data == YT.PlayerState.ENDED) {
console.log($('#player').remove());
done = true;
}
}
You have a fully working solution in here: http://jsfiddle.net/jibietr/ua57A/1/
A quick and dirty solution would be to use innerHTML to overwrite the iframe when the user closes the video with an onclick event. If the iframe is wrapped inside a with id = "iframeDiv", you can call the following function onclick of the close video button:
function hideIframe() {
document.getElementById("iframeDiv").innerHTML = '';
}
The iframe would reappear when the user opens the video:
function showIframe() {
document.getElementById("iframeDiv").innerHTML = '<iframe width="840" height="630" src="URLrel=0&showinfo=0;&autoplay=1;controls=0" frameborder="0" allowfullscreen></iframe>';
}
I have a HTML5 YouTube Player on my Website:
<iframe id="video1"
width="600"
height="283"
src="youtubeurl"
frameborder="0"
allowfullscreen></iframe>
That renders OK. Now I want to change the video being played based on a JavaScript function call:
function doSomething() { ... }
Here is what I've tried.
$("#video1").attr('src', 'otherURL' + '?' + "wmode=transparen");
$('#video1').hide();
setTimeout(function () {
$('#video1').show(); }, 100);
But nothing happens! How can I do that?
Have you tried embedding a YouTube player into your page? If you do this it will make your life easier trying to operate on the player functionality.
Some of the embedded player functions include:
loadVideoByUrl()
playVideo()
nextVideo()
You can find everything you need here in the YouTube JavaScript API
You can embed your player into an iframe using the examples detailed here.
To control YouTube player you'd better use YouTube API. It is pretty easy. check out this exaple http://jsfiddle.net/uLygZ/1/ I tried to make free of jQuery calls, but note that my scripts are executed inside document-ready handler.
For more information see https://developers.google.com/youtube/
I am writing a Browser Plugin and need to find a way to get the current time a YouTube Video playing on YouTube using JavaScript. I have been playing around in the Chrome JavaScript Console and haven't had any luck.
It appears that the chrome API only works with embedded video players not a video that is playing on on youtube.com. One option I looked into is in the share section of a video their is an input box for the "start at:" time that contains the current time of the video. I have tried using .value and .text on this input box and they both return undefined? Does anyone have any ideas?
ytplayer = document.getElementById("movie_player");
ytplayer.getCurrentTime();
See the api
Update: if it didn't work, also try player.playerInfo.currentTime (codepen live example)
Depends on what you want
player.getCurrentTime():Number
Returns the elapsed time in seconds since the video started playing.
player.getDuration():Number
Returns the duration in seconds of the currently playing video. Note
that getDuration() will return 0 until the video's metadata is loaded,
which normally happens just after the video starts playing.
http://code.google.com/apis/youtube/js_api_reference.html
Finally I found how to make it work on iOS (and Android too).
Actually, the whole youtube js api was broken for me if run on mobile browser.
Problem solved by creating player using new YT.Player as described in YouTube IFrame API.
Please note: only creating <iframe> from <div> placeholder works for mobile browsers at the time. If you try to use existing <iframe> in new YT.Player call, as mentioned in IFrame API, this will not work.
After player created, it's possible to use player.getCurrentTime() or player.getDuration() with player instance created.
Note: I had no luck calling this methods on player obtained with
player = document.getElementById(...) (from #JosephMarikle answer).
Only created player instance worked in mobile browsers.
Useful links:
YouTube IFrame API
YouTube JavaScript API
YouTube Player Demo
You can use Html5 Video API on youtube.com
var htmlVideoPlayer = document.getElementsByTagName('video')[0];
htmlVideoPlayer.currentTime
Note: It's not gonna work on Youtube Iframe API because Iframes are isolated. You cannot access the context of a Youtube IFrame .
In 2020, this works:
player.playerInfo.currentTime
full code:
see it live on codepen
Just FYI, There is a new iframe API for the YouTube player:
https://developers.google.com/youtube/iframe_api_reference
document.querySelector('video').currentTime
Stop at specific time youtube video and show notification box in GWD
<script>
var yid = document.getElementById("gwd-youtube_1");
var idBox = document.getElementById("box1");
pausing_function = function(event) {
var aa = setInterval(function() {
if (yid.getCurrentTime() > 8.0 && yid.getCurrentTime() < 8.1) {
yid.pause(yid);
idBox.style.opacity = 1;
console.log(yid.getCurrentTime() + "playing")
clearInterval(aa);
yid.removeEventListener("playing", pausing_function);
}
}, 100)
}
yid.addEventListener("playing", pausing_function);
var pausing_function_1 = function() {
if (yid.getCurrentTime() > 8.1) {
console.log(yid.getCurrentTime() + "pause")
// remove the event listener after you paused the playback
yid.removeEventListener("playing", pausing_function);
}
};
</script>
play video and hide notification
<script type="text/javascript" gwd-events="handlers">
window.gwd = window.gwd || {};
gwd.pauseVideo = function(event) {
var idBox = document.getElementById("box1");
idBox.style.opacity = 0;
};
</script>
<script type="text/javascript" gwd-events="registration">
// Support code for event handling in Google Web Designer
// This script block is auto-generated. Please do not edit!
gwd.actions.events.registerEventHandlers = function(event) {
gwd.actions.events.addHandler('gwd-youtube_1', 'playing', gwd.pauseVideo, false);
};
gwd.actions.events.deregisterEventHandlers = function(event) {
gwd.actions.events.removeHandler('gwd-youtube_1', 'playing', gwd.pauseVideo, false);
};
document.addEventListener("DOMContentLoaded", gwd.actions.events.registerEventHandlers);
document.addEventListener("unload", gwd.actions.events.deregisterEventHandlers);
</script>