Play Youtube Videos on Scroll Over
So one thing that I set out to do on a project was implement the new autoplay video that kinda works well on Facebook. Let’s do this with some Youtube videos.
When a video appears in your scroll view, it automatically starts to play on mute.
I use Youtube videos in a collage at Minneapolis Open Mic, a project I’m not yet finished with.
The first step is to implement Youtube Player api and get your play function ready.
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function playThis(elem) {
player = new YT.Player(elem.attr('id'), {
events: {
'onReady': function(){player.playVideo(); player.mute();}
}
});
}
This function will play the video of the selected iframe, the elem variable. It will also mute the video. So we want to trigger the play function when the element is in view.
$(window).scroll(function() {
clearTimeout($.data(this, 'scrollTimer'));
$.data(this, 'scrollTimer', setTimeout(function() {
// do something
isScrolledIntoView();
}, 250));
});
function isScrolledIntoView()
{
$('.collageYoutube').each(function(){
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(this).offset().top;
var elemBottom = elemTop + $(this).height();
if ((elemBottom <= docViewBottom) && (elemTop >= docViewTop))
{
playThis($(this));
}else{
pauseThis($(this));
}
});
}
What this does is checks to see if the scroll has ended for a quarter of a second. And then triggers a function that goes through all iframes with the class ‘collageYoutube’. It checks if they are visible on the screen and if they are, sends them to the playThis function you have earlier.
Fun little function. I’m currently working on a pause function for this.