Skip to content

Instantly share code, notes, and snippets.

@aabir
Created January 10, 2015 18:51
Show Gist options
  • Save aabir/9a40dd9e19475cb151a2 to your computer and use it in GitHub Desktop.
Save aabir/9a40dd9e19475cb151a2 to your computer and use it in GitHub Desktop.
Youtube video API for custom video control and thumbnail.
var player;
// this function gets called when API is ready to use
function onYouTubePlayerAPIReady() {
// create the global player from the specific iframe (#video)
player = new YT.Player('player', {
events: {
// call this function when player is ready to use
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(event) {
// bind events
var playButton = document.getElementById("video-play");
playButton.addEventListener("click", function() {
player.playVideo();
});
}
function onPlayerStateChange(event) {
/*
UNSTARTED -1
ENDED 0
PLAYING 1
PAUSED 2
BUFFERING 3
CUED 5
*/
if (event.data === YT.PlayerState.PLAYING) {
$('#player-picture, #video-play').hide();
if (!$('.video-frame').data('binded')) {
$('.video-frame').data('binded', true);
$('.video-frame').on('click', throttle(function(event) {
event.stopPropagation();
player.pauseVideo();
}, 100));
}
} else if (event.data === YT.PlayerState.ENDED || event.data === YT.PlayerState.PAUSED) {
$('#player-picture, #video-play').show();
} else if (event.data === YT.PlayerState.BUFFERING) {
$('#player-picture, #video-play').hide();
}
}
// Inject YouTube API script
var tag = document.createElement('script');
tag.src = "//www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
function throttle(fn, delay) {
var timer = null;
return function () {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment