Jquery Script to Scroll Page when href with target ID is Clicked

On single page websites, there are lots of anchor links connected on an ID selector. And it would be better if it will scroll up/down when you click it. For example, the go to top anchor is linked to #header.

The script below will help you give a cool animation effect while navigating to your site. It will scroll the page to your target ID while giving a smooth feel for the user.

<script type="text/javascript">
  $(function() {
    $('#header li a[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) {
          var targetOffset = $target.offset().top;
          $('html,body').animate({
            scrollTop: targetOffset - 103 // 103 is height of fixed header
          }, 500);
          return false;
        }
      }
    });
  });
  </script>

Now let’s inspect the javascript above. You can just simple copy and paste is right after a jquery script or at the bottom of the page. But watchout for line 3 and line 10. Because this correspondes to the anchor link and the offset.

Anchor links for ID selector for fixed header

You can still scroll the page even if you have a fixed header. The ploblem is some parts are covered. The solution is on line 10. Offset allows you to have a sort of distance from the top of the screen to your target ID.