In-Page Smooth Scroll Animation to Anchor Script

If you have a page with links to sections within the same web page, here is a ready-to-go jQuery script for performing smooth transitions that scroll (rather than jump immediately) to the link’s destination within the page. Remember to include <script> … </script> tags before and after the below script and insert the code to your page’s footer section (before the closing </body> tag).

// Select all links with hashes
$('a[href*="#"]')
  // Remove links that don't actually link to anything
  .not('[href="#"]')
  .not('[href="#0"]')
  .click(function(event) {
    // On-page links
    if (
      location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 
      && 
      location.hostname == this.hostname
    ) {
      // Figure out element to scroll to
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      // Does a scroll target exist?
      if (target.length) {
        // Only prevent default if animation is actually gonna happen
        event.preventDefault();
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000, function() {
          // Callback after animation
          // Must change focus!
          var $target = $(target);
          $target.focus();
          if ($target.is(":focus")) { // Checking if the target was focused
            return false;
          } else {
            $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
            $target.focus(); // Set focus again
          };
        });
      }
    }
  });

The method that I use to connect the links to their content is something like:
<a href=”#firstlink”>Go to First Link</a> and
<div id=”firstlink”>This is the content the browser will smoothly scroll to!</div>