Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
jQuery: Scroll element to the middle of the viewport
(function($) {
/**
* jQuery function to scroll the viewport middle to the element.
*/
$.fn.scrollToMiddle = function(options) {
var settings = $.extend({
duration: 1000
}, options );
return this.each(function() {
var $el = $(this);
var elOffset = $el.offset().top;
var elHeight = $el.height();
var windowHeight = $(window).height();
var offset;
if (elHeight < windowHeight) {
offset = elOffset - ((windowHeight / 2) - (elHeight / 2));
}
else {
offset = elOffset;
}
$('html, body').animate({
scrollTop: offset
}, settings.duration);
});
};
}(jQuery));
// Example for scrolling to anchors (UNTESTED!):
$('a[href^="#"]:not([href="#"]):not([role="tab"])').click(function (e) {
if (location.hostname == this.hostname) {
var target = $(this.hash);
$target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if ($target.length) {
$target.scrollToMiddle({duration: 500}});
return false;
}
}
});
@JPustkuchen

This comment has been minimized.

Copy link
Owner Author

@JPustkuchen JPustkuchen commented Dec 16, 2020

Deprecated. See scrollToViewport.js gist!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment