Smooth page scrolling using JavaScript

  • Published:
  • Updated:

You can find many examples of solving this problem, for example, on jQuery. But in some cases, when other effects are not needed on the site, connecting a whole library is stupid. It makes much more sense to use pure JavaScript.

document.body.addEventListener('click', function (e) {
    if (e.target.tagName === 'A' && e.target.getAttribute('href').startsWith('#')) {
       e.preventDefault();
 
       const blockID = e.target.getAttribute('href').slice(1);
       const targetBlock = document.getElementById(blockID);
 
       if (targetBlock) {
          targetBlock.scrollIntoView({
             behavior: 'smooth',
             block: 'start'
          });
       }
    }
});
Serhii Kolomiitsev
Programmer, i have been working with WordPress since 2010.

Leave a Reply

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