Skip To Content

How to Smooth Scroll with a simple Javascript

Kevin Doherty

Creative Director

Date

Oct. 9, 2014

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

[codepen_embed height=”550″ theme_id=”0″ slug_hash=”xdbnw” default_tab=”result” user=”nvision”]See the Pen Fixed header scroll to one pager by Kevin Doherty (@nvision) on CodePen.[/codepen_embed]

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

Book with us

Let’s accomplish what you are looking for, our team of experts are here for you.

Let's work together

Warning: Working with our team may result in excessive creativity, uncontrollable 'aha' moments, and an addiction to perfect pixels. Please proceed with caution.