Skip to content

Instantly share code, notes, and snippets.

@planetoftheweb
Last active May 13, 2020 11:40
Show Gist options
  • Save planetoftheweb/6729f849d7db31061b2e to your computer and use it in GitHub Desktop.
Save planetoftheweb/6729f849d7db31061b2e to your computer and use it in GitHub Desktop.
Smooth Scrolling Animation with an Offset...uses === and a predefined offset
//Use smooth scrolling when clicking on navigation
$('.navbar a[href*=\\#]:not([href=\\#])').click(function() {
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) {
$('html,body').animate({
scrollTop: target.offset().top-topoffset+2
}, 500);
return false;
} //target.length
} //click function
}); //smooth scrolling
@kevinemyers
Copy link

For those using a version of jquery above 1.11.2, this code will throw an exception[1]. The hash now needs to be escaped or quoted.

Thus:
$('.navbar a[href*=#]:not([href=#])')
becomes:
$('.navbar a[href*=\\#]:not([href=\\#])')

[1] 1.12.0 vs 1.11.2 selectors with # broken #2824

@planetoftheweb
Copy link
Author

Thanks...I updated the code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment