I am trying to implement a small code with which I can get a smooth scroll when I click on the anchor (and the anchor name appears after the animation), and I would like to return to the top of the page if I click the browser back button and refresh the URL (without the name #anchor).
Here is the code:
$(function() {
$('a[href*=#]:not([href=#])').click(function(event) {
event.preventDefault();
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) {
var hash = this.hash;
$('html,body').animate({ scrollTop: target.offset().top - 55}, 300, function() {
location.hash = hash;
href = window.location.href;
history.pushState({page:href}, null, href);
});
return false;
}
}
});
$(window).bind('popstate', function(event) {
var state = event.originalEvent.state;
var target = window.location.href.split('#');
var href = target[0];
if (state) {
$('html,body').animate({ scrollTop: 0 }, 300, function() {
window.location.href = href;
})
}
});
window.onload = function() {
history.replaceState({ path: window.location.href }, '');
}
});
All of the above features work well in Safari and Chrome. But this does not apply to Firefox: after performing a smooth scrolling, I need to double-click the "Back" button to redirect it to the top of the page.
I saw https://stackoverflow.com/a/1666547/ ... and tried to do with and without event.preventDefault, also putting only:
$('html').animate
or $('body').animate
but the behavior remains the same.
- , .