It happens because in the blog post, the links, are ACTUAL links, meaning they change page, causing a complete request to the server and a reload of all Javascript. The click event is gone by the time the next page is up, which is where you want to scroll. Luckily we get a hash with us, which gives us a hook we can use to animate afterwards.
This should do it for you :)
$(document).ready(function(){
var idOfSection = window.location.hash.substring(1);
var $sectionToScrollTo = $('#'+idOfSection);
if($sectionToScrollTo.length > 0){
var offset = $sectionToScrollTo.offset().top-49;
$('html, body').animate({scrollTop: offset },1800);
}
});
If you want it to scroll from the top, add: $('html, body').animate({scrollTop: 0},0);
as the first thing in the if statement.
To improve further
$(document).ready(function(){
var sectionId = window.location.hash;
scrollToSection(sectionId);
$('body').on('click', 'nav a', function(){
var secId = this.hash;
scrollToSection(secId);
}
});
function scrollToSection(sectionId){
var $sectionToScrollTo = $(sectionId);
if($sectionToScrollTo.length > 0){
var offset = $sectionToScrollTo.offset().top-49;
$('html, body').animate({scrollTop: offset },1800);
}
}
Note that I haven't tested the second code example.