JavaScript

Smooth Scrolling to Anchor Using JavaScript

Last updated: 09.10.2025
Views: 217

Smooth scrolling is a popular web design feature that enhances user experience by allowing seamless navigation between sections of a webpage. Instead of abrupt jumps, smooth scrolling creates a fluid motion, making transitions more visually appealing. In this article, we’ll explore how to implement smooth scrolling using JavaScript. It’s not difficult at all to implement this. Let’s dive in and make your website navigation feel effortless!

HTML

<ul class="nav-block">
  <li><a href="#first">First block</a></li>
  <li><a href="#second">Second block</a></li>
  <li><a href="#third">Third block</a></li>
  <li><a href="#fourth">Fourth block</a></li>
</ul>

The id attribute is used to designate an anchor. For example:

<div id="first">
Some your content...
</div>

JavaScript

const els = document.querySelectorAll('.nav-block a');

els.forEach((el) => {

  el.addEventListener('click', (ev) => {
    ev.preventDefault();

    const id = el.getAttribute('href').slice(1);
    const block = document.getElementById(id);

    if (block) {
      window.scrollTo({
        top: block.offsetTop,
        behavior: 'smooth',
      });
    }
  });
});

If you use jQuery in your project, then you can write almost the same thing using this JavaScript library.

jQuery

$('.nav-block a').on('click', function(ev) {
    ev.preventDefault();
  
    const id  = $(this).attr('href');
    const top = $(id).offset().top;
  
    $('body,html').stop().animate({scrollTop: top}, 1000);
});

1000 – scroll time in milliseconds

author
Author: Igor Rybalko
I have been working as a front-end developer since 2014. My main technology stack is Vue.js and WordPress.

Similar posts:

Leave a Reply

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