Skip To Content
Development

How to Smooth Scroll with a simple Javascript

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

Comments

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

Request a Quote

If you’re ready to change the trajectory of your business and
excited to partner with the right team to get the job done.