• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Navigation / Scroll to an element smoothly

Scroll to an element smoothly

Scroll to an element smoothly

This snippet produces a smooth scrolling implementation which also allows us to customize the animation effect and duration.

Let’s say the navigation consists of some a elements:

<a href="#section-1" class="trigger"></a>
<a href="#section-2" class="trigger"></a>
...

<div id="section-1">...</div>
<div id="section-2">...</div>

Clicking the link will scroll the page to a particular element that can be determined by the href attribute.

const triggers = [].slice.call(document.querySelectorAll('.trigger'));
triggers.forEach(function(ele) {
    ele.addEventListener('click', clickHandler);
});

The clickHandler function handles the click event of a navigation element. It determines the target section based on the href attribute. Notice that we will scroll to the target section ourselves, hence the default action will be ignored:

const clickHandler = function(e) {
    // Prevent the default action
    e.preventDefault();

    // Get the `href` attribute
    const href = e.target.getAttribute('href');
    const id = href.substr(1);
    const target = document.getElementById(id);

    scrollToTarget(target);
};

Customize the animation

Currently, we move to the target equally per millisecond. We move the same distance every milliseconds.

If you want, you can replace the current linear movement with other easing functions. Look at this website to imagine how each easing produces different animations.

The code below uses the easeInQuad animation:

const easeInQuad = function(t) {
    return t * t;
};

const loop = function(currentTime) {
    ...
    const percent = Math.min(time / duration, 1);
    window.scrollTo(0, startPos + diff * easeInQuad(percent));
});

Source

https://htmldom.dev/scroll-to-an-element-smoothly/

Navigation

Related Snippets:

  • Using the Target Attribute
  • Ticker
  • Drag to scroll
  • Check if touch events are supported

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers