I'm trying to implement a small code with which I can get smooth scrolling when I click on anchor (and anchor name appears after animation) and I would like to return to the top of page if I push on the back button of the browser and update the URL (without #anchor name).
Here's the code :
$(function() {
// Smooth scrolling when clicking on anchor
$('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;
}
}
});
// Get smooth scrolling to the top whith back button of browser
$(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;
})
}
});
// First page loading
window.onload = function() {
history.replaceState({ path: window.location.href }, '');
}
});
All the above functionalities work well under Safari and Chrome. But this is not the case with Firefox: once smooth scrolling down is performed, I need to click twice on back button to be redirected on the top of page.
I have seen this other question on stackoverflow and tried to do with and without event.preventDefault, also by putting only :
$('html').animate
or $('body').animate
but the behavior is the same.
If someone could see why it doesn't work.
Thanks