Created
August 14, 2019 12:42
-
-
Save JPustkuchen/d436d189d1840489454b982e90559999 to your computer and use it in GitHub Desktop.
jQuery: Scroll element to the middle of the viewport
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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; | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Deprecated. See scrollToViewport.js gist!