Skip to content

Instantly share code, notes, and snippets.

@JPustkuchen
Created August 14, 2019 12:42
Show Gist options
  • Save JPustkuchen/d436d189d1840489454b982e90559999 to your computer and use it in GitHub Desktop.
Save JPustkuchen/d436d189d1840489454b982e90559999 to your computer and use it in GitHub Desktop.
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
Copy link
Author

Deprecated. See scrollToViewport.js gist!

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