I\'ve been trying to add a smooth scrolling function to my site for a while now but can\'t seem to get it to work.
Here is my HTML code relating to my navigation:<
What onetrickpony posted is okay, but if you want to have a more general solution, you can just use the code below.
Instead of selecting just the id of the anchor, you can make it bit more standard-like and just selecting the attribute name of the -Tag. This will save you from writing an extra id tag. Just add the smoothscroll class to the navbar element.
What changed
1) $('#nav ul li a[href^="#"]') to $('#nav.smoothscroll ul li a[href^="#"]')
2) $(this.hash) to $('a[name="' + this.hash.replace('#', '') + '"]')
Final Code
/* Enable smooth scrolling on all links with anchors */
$('#nav.smoothscroll ul li a[href^="#"]').on('click', function(e) {
// prevent default anchor click behavior
e.preventDefault();
// store hash
var hash = this.hash;
// animate
$('html, body').animate({
scrollTop: $('a[name="' + this.hash.replace('#', '') + '"]').offset().top
}, 300, function(){
// when done, add hash to url
// (default click behaviour)
window.location.hash = hash;
});
});