I am trying to make smooth scrolling in a single page application. In order to do this I am using window.location.hash statement in a click event handler like:
$('a').on('click', function(event) {
event.preventDefault();
let hash = this.hash;
if (hash !== '') {
window.location.hash = hash
// _scrollTo();
}
})
I am binding window's hashchange event to the above _scrollTo() function so that when user tries to get the url with hash, application should scroll there:
$(window)
.on("hashchange", _scrollTo)
.trigger("hashchange")
Scrolling function is like this:
const _scrollTo = function () {
var destination = $('body').find(window.location.hash);
_scrollToDestination(destination, configMap.duration);
}
I need to use this function because of fixed header on top of page, I dont want the scrolling to a section would be under header and user does not see that
const _scrollToDestination = function (destination, duration) {
let headerHeight = $('header').outerHeight(true);
$('html, body').animate({
scrollTop: destination.offset().top - headerHeight
}, duration);
}
The problem is when I use the window.location.hash statement in click handler, event handler behaves as if default behaviour not prevented and I get weird results.
Any help is appreciated. Thanks.