Skip to content

Instantly share code, notes, and snippets.

@anchietajunior
Created June 14, 2017 19:06
Show Gist options
  • Save anchietajunior/a7d29d181e1c32bbd64d7f170ce3f292 to your computer and use it in GitHub Desktop.
Save anchietajunior/a7d29d181e1c32bbd64d7f170ce3f292 to your computer and use it in GitHub Desktop.
Get Duration and CurrenTime of an Youtube Iframe and Calculates percentage
<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<div>Current Time: <span id="time"></span></div>
<script>
var timeupdater;
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;
var videotime = 0;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {}
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && done == false) {
var duration = parseInt(Math.round(player.getDuration()) * 10/100);
console.log(duration);
function updateTime() {
if(player && player.getCurrentTime) {
videotime = parseInt(Math.round(player.getCurrentTime()));
if(videotime >= duration){
done = true;
clearTimeout(timeupdater);
console.log("Opa! Completou os 10%");
}
console.log(Math.round(videotime));
document.getElementById("time").innerHTML = videotime;
}
}
timeupdater = setInterval(updateTime, 1000);
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment