The Javascript

Smooth Scroll with a simple Javascript, you can include in your projects when you’d like to create a smooth transition from an anchor link to a targeted element by ID. This is great to use when developing one pager style websites, especially with a fixed header navigation.

$(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({
            //the 205 is a fixed header offset
          scrollTop: target.offset().top - 205
        }, 1000);
        return false;
      }
    }
  });
});

Setting Things Up for Smooth Scroll

Once you’ve included the Javascript into your page, all that is left is assigning and ID to the element you’d like to scroll to like so:
<div id="target">scroll to here</div>

For the link simply put the same ID in your href attribute like so:
<a href="#target">Click me to go to the targeted element</a>

Demo

See the Pen Fixed header scroll to one pager by Kevin Doherty (@nvision) on CodePen.0

Script Credits: https://www.learningjquery.com/2007/10/improved-animated-scrolling-script-for-same-page-links

Originally published on

Leave a Reply

Your email address will not be published. Required fields are marked *

Have Any Questions?

Speak with a
Digital Expert

  • Looking to increase leads?
  • Maximize profits?
  • Redesign your website?
  • Sell Online?
  • Build an App?

Let's Discuss Your Next Project

  • This field is for validation purposes and should be left unchanged.