Skip to content

Instantly share code, notes, and snippets.

@JPustkuchen
Created December 16, 2020 08:00
Show Gist options
  • Save JPustkuchen/bc2142b744f1fd483bbddc347f22c7d4 to your computer and use it in GitHub Desktop.
Save JPustkuchen/bc2142b744f1fd483bbddc347f22c7d4 to your computer and use it in GitHub Desktop.
(function($) {
/**
* jQuery function to scroll the element into the viewport with
* typical options and menu bar exclusion.
*/
$.fn.scrollToViewport = function(options) {
var settings = $.extend({
/**
* The scroll duration.
*/
duration: 1000,
excludeElement: null,
toViewportArea: 'top',
}, options );
return this.each(function() {
var $el = $(this);
var elOffset = $el.offset().top;
if(settings.excludeElement && $(settings.excludeElement).length > 0 && $(settings.excludeElement).is(':visible')){
elOffset = elOffset - $(settings.excludeElement).outerHeight();
}
var elHeight = $el.height();
var windowHeight = $(window).height();
var offset;
switch (settings.toViewportArea) {
case 'middle':
if (elHeight < windowHeight) {
offset = elOffset - ((windowHeight / 2) - (elHeight / 2));
}
else {
offset = elOffset;
}
break;
case 'bottom':
offset = elOffset - ((windowHeight) - (elHeight));
break;
case 'top':
offset = elOffset;
default:
break;
}
$('html, body').animate({
scrollTop: offset
}, settings.duration);
});
};
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment