The mysterious case of jquery scrolling solved!

We can all easily google and find all sort of different methods/codes to get the smooth scrolling to hashtags; either allow you to smooth scroll to the hashtag when you click on the link from another page (click href=”/some-page/#jumphere”) or they allow you to smooth scroll on the same page (click href=”#jumphere”)

However, what if you need both?

You cant do both together; and if you do, either the two sets of codes will contradict each other; or the window will make a split second jump to #jumphere the very moment you click the href=”/some-page/#jumphere”, before jumping back to the original position to scroll to the #jumphere again ( which also means its jerky.)

After spending a few hours trying to figure out a way, I have finally found the way to do both.

First you have this code (just above ) for jumping from another page to your target page, and then scroll to your hashtag:

$(document).ready(function() {
$('html, body').hide();

if (window.location.hash) {
setTimeout(function() {
$('html, body').scrollTop(0).show();
$('html, body').animate({
scrollTop: $(window.location.hash).offset().top
}, 1000)
}, 0);
}
else {
$('html, body').show();
}
});

and then you add this code (just above ) below for the scrolling to hashtag within the same page from any button set with the class “scroll”:

$(document).ready(function () {
if(window.location.href.indexOf("page-name") > -1) {
$(".scroll").click(function(event){
event.preventDefault();
//calculate destination place
var dest=0;
if($(this.hash).offset().top > $(document).height()-$(window).height()){
dest=$(document).height()-$(window).height();
}else{
dest=$(this.hash).offset().top;
}
//go to destination
$('html,body').animate({scrollTop:dest}, 1000,'swing');
});

}
});

If you noticed, there is this line: if(window.location.href.indexOf(“page-name”) > -1) { , change the “page-name” to the page’s url (for example, if the target page is this blog post’s page, the “page-name” would be “the-mysterious-case-of-jquery-scrolling-solved”. This is to ensure that this code only runs inside this particular page. Because if you do not, the code event.preventDefault(); will disable the button, resulting you unable to jump from that external page, into this target page.

Finally, we still need a universal scrolling to hashtag code that do not meet the above’s problem:

$(window).load(function(){
$('a').click(function(){
$('html, body').animate({
scrollTop: $( $(this).attr('href') ).offset().top
}, 1000);
return false;
});

This code will ensure that all links with a hashtag will automatically have smooth scrolling.

Thats all!

If you dun understand, email me at limmingji@gmail.com to ask me your question. Cheers!