Smooth Scrolling to Anchor with jQuery


The days of abruptly jumping to an anchor link within a page are over. Ok, maybe that is a little drastic, but honestly with all the advancements in HTML5 and CSS3, there really isn’t any reason why anyone should be abruptly thrust down a page to an anchor link.

You’ve probably seen this effect on some of your favorite sites. You click on a link, and the page smoothly and gracefully scrolls down to a specific section of content. This transition is easy on the eyes, it’s appealing, and damnit – it’s just plain cool!


I’ve worked with clients that are fascinated by this effect, and more often than not they seem to think that it would take some great engineering feet to accomplish. This isn’t the case! In fact, you can accomplish this simple effect with just a few lines of jQuery!

We’ll utilize jQuery’s built-in function scrollTop() to do our heavy lifting.

View Demo

The jQuery

Here is a simple function I wrote that will accomplish this effect.

The Explanation

The scrollToAnchor function takes in a variable, in this case ‘aid’ (or a ID, as in anchor ID). The function than generates an a tag with that variable – one that matches the anchor tag you put on your page.

Then, the jQuery function scrollTop is put to use to animate the page and gracefully scroll up or down to the new location.

In my above example, I’ve chosen to fire this function on all a tags, but you can specify which you would like by using a more specific selector. On click, we grab the href attribute, remove the # symbol, and send that variable to our scrollToAnchor function.

This example works if your HTML is set up like so:

With the jQuery that I wrote above, as long as the name matches the href, it will work automatically on all a tags!

Check out my example to see it in action!

View Demo

See? It’s not that complicated. Give it a try and let me know if you have a better solution!

Update 3-11-2014

I admit that when I wrote this post in August of 2013, I didn’t fully flesh it out and find the best solution. It does work, but needs a few minor tweaks to work in ideal situations (check out the comments in this post to see what I’m talking about).

James Pederson was kind enough to rework this function to iron out those tweaks I was talking about, and I’m happy to share it with you here (with full credit going to James of course).