Scroll To Anchor using JavaScript

Scroll To Anchor using JavaScript
Code Snippet:Smooth Scrolling Anchor pure JS
Author: Mary Pieroszkiewicz
Published: May 5, 2024
Last Updated: May 5, 2024
Downloads: 60
License: MIT
Edit Code online: View on CodePen
Read More

This code enables a smooth scroll to Anchor using JavaScript when menu items are clicked. It works by detecting click events on menu items and calculating the scroll position of the target section. This functionality helps create a user-friendly navigation experience on single-page websites.

You can use this code on single-page websites to create smooth scrolling navigation. It enhances user experience by providing seamless transitions between sections. Additionally, it adds a modern touch to your website’s design, improving overall aesthetics.

How to Create Scroll To Anchor using JavaScript

1. Start by creating the HTML structure for your single-page website. Define sections with unique IDs that you want to navigate to. Also, create a navigation menu with links pointing to these sections.

<div class="page-wrapper">
  <menu class="menu">
    <ul class="menu-list">
      <li class="menu-item"><a href="#" data-target="block-1">First</a></li>
      <li class="menu-item"><a href="#" data-target="block-2">Second</a></li>
      <li class="menu-item"><a href="#" data-target="block-3">Third</a></li>
    </ul>
  </menu>
  <div class="wrapper">
    <div id="block-1" class="block">
      First
    </div>
    <div id="block-2" class="block">
      Second
    </div>
    <div id="block-3" class="block">
      Third
    </div>
  </div>
</div>

2. Apply basic CSS to style your sections and navigation menu. You can customize the styles according to your design preferences.

html {
  scroll-behavior: smooth;
}

.menu {
  position: fixed;
  top: 0;
  padding-left: 0;
}

.menu-list {
  list-style: none;
  margin: 0;
  padding: 0;
  border-radius: 3px;
  overflow: hidden;
}

.menu-item {
  margin-left: 0;
  padding: 0;
  ;
  background: rgba(255, 255, 255, .83);
  transition-duration: .3s;
  cursor: pointer;
}

.menu-item:hover {
  background: rgba(255, 255, 255, 1);
}

.menu-item a {
  padding: 12px 24px;
  color: rgba(0, 0, 0, .83);
  text-decoration: none;
  display: block;
}

.block {
  width: 100%;
  height: 100vh;
  color: #fff;
  font-size: 5em;
  display: flex;
  align-items: center;
  justify-content: center;
}

#block-1 {
  background: #2196F3;
}

#block-2 {
  background: #FF5722;
}

#block-3 {
  background: #795548;
}

3. Copy and paste the following JavaScript code into your project. This code contains functions for smooth scrolling and event listeners to handle menu item clicks.

const list = document.getElementsByClassName('menu-list')[0];

// easing functions http://goo.gl/5HLl8
Math.easeInOutQuad = function(t, b, c, d) {
  t /= d / 2;
  if (t < 1) {
    return c / 2 * t * t + b
  }
  t--;
  return -c / 2 * (t * (t - 2) - 1) + b;
};

Math.easeInCubic = function(t, b, c, d) {
  var tc = (t /= d) * t * t;
  return b + c * (tc);
};

Math.inOutQuintic = function(t, b, c, d) {
  var ts = (t /= d) * t,
    tc = ts * t;
  return b + c * (6 * tc * ts + -15 * ts * ts + 10 * tc);
};

// requestAnimationFrame for Smart Animating http://goo.gl/sx5sts
var requestAnimFrame = (function() {
  return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) {
    window.setTimeout(callback, 1000 / 60);
  };
})();

function scrollTo(to, callback, duration) {
  // because it's so fucking difficult to detect the scrolling element, just move them all
  function move(amount) {
    document.documentElement.scrollTop = amount;
    document.body.parentNode.scrollTop = amount;
    document.body.scrollTop = amount;
  }

  function position() {
    return document.documentElement.scrollTop || document.body.parentNode.scrollTop || document.body.scrollTop;
  }
  var start = position(),
    change = to - start,
    currentTime = 0,
    increment = 20;
  duration = (typeof(duration) === 'undefined') ? 500 : duration;
  var animateScroll = function() {
    // increment the time
    currentTime += increment;
    // find the value with the quadratic in-out easing function
    var val = Math.easeInOutQuad(currentTime, start, change, duration);
    // move the document.body
    move(val);
    // do the animation unless its over
    if (currentTime < duration) {
      requestAnimFrame(animateScroll);
    } else {
      if (callback && typeof(callback) === 'function') {
        // the animation is done so lets callback
        callback();
      }
    }
  };
  animateScroll();
}

list.addEventListener('click', e => {
  const {
    target
  } = e;
  const to = target.getAttribute('data-target');
  const element = document.getElementById(to);
  const bodyRect = document.body.getBoundingClientRect();
  const elemRect = element.getBoundingClientRect();
  const offset = elemRect.top - bodyRect.top;
  scrollTo(offset, null, 300);
});

Congratulations! You’ve successfully implemented smooth scroll navigation on your single-page website using JavaScript. This enhances user experience and adds a modern touch to your website’s design. Feel free to customize and expand upon this code to suit your specific needs.

Leave a Comment