Skip to content

Instantly share code, notes, and snippets.

@Kcko
Created May 12, 2020 10:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kcko/a15578b53a4d5525ee29f648788ad619 to your computer and use it in GitHub Desktop.
Save Kcko/a15578b53a4d5525ee29f648788ad619 to your computer and use it in GitHub Desktop.
(function($){
$.fn.isInViewport = function(){
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return (elementBottom > viewportTop && elementTop < viewportBottom);
};
$.fn.youTubeImage = function(){
this.each(function(){
var src = $(this).find('iframe').attr('title'); //.attr('src')
var arr = src.split('/');
if(typeof arr[2] != 'undefined'){
if(arr[2].indexOf('youtube')+1){
$(this).addClass('is-youtube');
}
}
if(arr.length){
var id = arr[arr.length-1].replace(/^(.*)\?(.*)$/, '$1');
var image = 'http://img.youtube.com/vi/' + id + '/0.jpg';
$(this).css({backgroundImage:'url(' + image + ')'});
}
var href = 'https://www.youtube.com/watch?v=' + id;
$(this).find('a').attr({ href: href, target: '_blank'});
});
return this;
};
$.fn.showWhenScrolled = function(){
var self = this;
this.init = function(){
self.each(function(){
var frame = $(this).find('iframe');
if($(this).isInViewport()){
if(!frame.attr('src')){
frame.attr({ src : frame.attr('title') });
}
}
});
};
$(window).on('scroll resize orientationchange', function(){
self.init();
});
self.init();
return this;
};
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment