Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
(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