Created
May 20, 2019 13:08
-
-
Save waqashassan98/6d82cf550d345911e615e103ef9e69c8 to your computer and use it in GitHub Desktop.
Youtube API Embed, Auto Start on scroll to its position and resonsive video
This file contains hidden or 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
<!-- Style --> | |
<style> | |
#y_video_container{ | |
position: relative; | |
width: 100%; | |
height: 0; | |
padding-bottom: 56.25%; | |
} | |
#y_video_container>iframe{ | |
position: absolute; | |
top: 0; | |
left: 0; | |
width: 100%; | |
height: 100%; | |
} | |
</style> | |
<!-- HTML --> | |
<div id="y_video_container"><div id="i_video"></div></div> | |
<!-- Script --> | |
<script> | |
function getPosition(el) { | |
var x = 0, | |
y = 0; | |
while (el != null && (el.tagName || '').toLowerCase() != 'html') { | |
x += el.offsetLeft || 0; | |
y += el.offsetTop || 0; | |
el = el.parentElement; | |
} | |
return { x: parseInt(x, 10), y: parseInt(y, 10) }; | |
} | |
var player; | |
var YTdeferred = jQuery.Deferred(); | |
window.onYouTubeIframeAPIReady = function() { | |
YTdeferred.resolve(window.YT); | |
}; | |
// embedding youtube iframe api | |
// https://developers.google.com/youtube/iframe_api_reference#Getting_Started | |
var tag = document.createElement('script'); | |
tag.src = "https://www.youtube.com/iframe_api"; | |
var firstScriptTag = document.getElementsByTagName('script')[0]; | |
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); | |
jQuery(document).ready(function(){ | |
YTdeferred.done(function(YT) { | |
player = new YT.Player('i_video', { | |
videoId: 'C_uGtENV83A', | |
playerVars: {rel: 0, showinfo: 0, ecver: 2, modestbranding: 1}, | |
events: { | |
'onReady': onPlayerReady, | |
// 'onStateChange': onPlayerStateChange | |
} | |
}); | |
}); | |
}); | |
function onPlayerReady(){ | |
jQuery(window).on('scroll', function(){ | |
var dv = document.getElementById('y_video_container'); | |
var v = document.getElementById('i_video'); | |
if ((window.scrollY < (getPosition(dv).y + dv.offsetHeight)) && ((window.scrollY + window.outerHeight) > getPosition(dv).y)) { | |
player.playVideo(); | |
jQuery(window).off('scroll'); | |
console.log("here"); | |
} | |
}); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment