Skip to content

Instantly share code, notes, and snippets.

@clickstudio
Last active September 4, 2019 02:48
Show Gist options
  • Save clickstudio/e5275a788b0259faf316a7237f4a6f90 to your computer and use it in GitHub Desktop.
Save clickstudio/e5275a788b0259faf316a7237f4a6f90 to your computer and use it in GitHub Desktop.
Just add the YouTube video ID to the 'video-id' data attribute
<div class="youtube_video_lazy_load"
data-video-id="AddYouTubeVideoIdHere"
data-iframe-width="853"
data-iframe-height="480"
data-iframe-src-url-vars="rel=0&showinfo=0&&mute=1&disablekb=1">
</div>
var youtube_videos_loaded = 0;
function loadYoutubeVideos() {
$('.youtube_video_lazy_load').each(function () {
if (youtube_videos_loaded == 0) {
var videoID = $(this).data("video-id");
var iframeWidth = $(this).data("iframe-width");
var iframeHeight = $(this).data("iframe-height");
var iframeSrcVars = $(this).data("iframe-src-url-vars");
if (videoID) {
var iframe = document.createElement("iframe");
iframe.setAttribute("frameborder", "0");
iframe.setAttribute("allowfullscreen", "");
iframe.setAttribute("src", "https://www.youtube.com/embed/" + videoID + "?" + iframeSrcVars);
iframe.setAttribute("width", iframeWidth);
iframe.setAttribute("height", iframeHeight);
/*iframe.setAttribute("allow", "accelerometer; encrypted - media; gyroscope; picture - in -picture");*/
$(this).html(iframe);
}
}
});
youtube_videos_loaded = 1;
}
var lastScrollTop = 0;
$(window).scroll(function (event) {
var st = $(this).scrollTop();
if (st > lastScrollTop) {
loadYoutubeVideos();
} else {
// up scroll code
}
lastScrollTop = st;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment