Created
June 14, 2017 19:06
-
-
Save anchietajunior/a7d29d181e1c32bbd64d7f170ce3f292 to your computer and use it in GitHub Desktop.
Get Duration and CurrenTime of an Youtube Iframe and Calculates percentage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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