Smooth scroll anchor links in html

By | August 8, 2016

What is Smooth Scroll

Smooth scroll is a very common feature for almost all types of modern websites. We often see it on many websites and sometimes we may need it on our own. Now a day, this smooth scroll is very popular. Developers use it to increase the functionality and also for better user experience. We can use smooth scroll not just because it looks good, but also it gives the user a greater experience. It is mostly used in single landing page sites where all the main sections are in same page. Smooth scrolling uses the # anchor links of a webpage.

As you already know # links are used to link inside a page because of the target areas which are inside the same page. The main code is in JavaScript but it can easily be implemented in html too. So today, I will show how to create smooth scrolling anchor links or # links on your webpage.

How to make smooth scroll

This is very easy process. All we need to do is to have a webpage where all the different sections have an id so that the navigation menu can target that location. Let’s say we want to enable it on our navigation menu and the menu items will target those specific ids so that when a user clicks on it, that menu should take them to the desired location.

In this demonstration, I will use one of my previously converted html page and implement smooth scrolling there. So, first of all, let’s give each of my div an id.

smooth scroll on anchor links

And now let’s target those IDs from my navigation menu and also check if those are working properly.

smooth scroll on a webpage

We are almost done, as our links are working properly, now we need to enable the smooth scrolling. Just a simple block of JavaScript will do the trick. On your webpage footer just before the ending of the body tag insert this code inside a script tag:

//enabling smooth scroll
$(function() {
  $('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
        }, 1000);
        return false;


I got this code from CSS Tricks, you can also go there and find this code. Copy this code and insert it inside script tag and see the magic. Smooth scrolling will work just fine. Since the code is fully working, you can either keep it in your index file or you can put the code maybe in another JavaScript file

So, if you have done everything right, your code will work properly. As always, I recorded this whole process in a video of 06.07. If you want, you can watch it on YouTube. Please like, comment and subscribe to my YouTube channel for more videos.


Facebook Comments

Leave a Reply