I've got a link that scrolls to areas of the same page. So the page doesn't jump around, I've added some JavaScript smooth scrolling (see below).
The issue is, the script scrolls the page to the top of the target div. It does this with some easing, so it slows down as it gets to the final div. This is fine, but if the last div is less than the height of the browser window, it will never be able to scroll to the top of the div. It just hits the bottom of the page and its looks broken as there is no easing.
I've tried several ways to make the final div scroll to the bottom of the div, but to no avail. Any ideas how to do this?
I've made a jsfiddle of the issue here: https://jsfiddle.net/gky7y6gu/2/
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
I added some logic to make sure the scrollTop never exceeds the height of the body minus the height of the window. This way the easeOut is always visible.
https://jsfiddle.net/gky7y6gu/3/
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
if (target.length) {
var scrollTo = target.offset().top;
var bodyHeight = $('body').height();
var windowHeight = $(window).height();
if (bodyHeight - windowHeight < scrollTo) {
scrollTo = bodyHeight - windowHeight;
}
$('html,body').animate({
scrollTop: scrollTo
}, 1000);
return false;
}
}
});
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments