How to implement smooth scrolling to anchor links on a webpage using JavaScript?

To implement smooth scrolling to anchor links on a webpage using JavaScript, you can follow these steps:

  1. Attach a click event listener to all anchor links on your webpage.
  2. In the event handler, prevent the default behavior of anchor links (to instantly jump to the target) using event.preventDefault().
  3. Get the target element of the anchor link using document.querySelector(target), where target is the value of the href attribute of the anchor link (including the # symbol).
  4. Calculate the scroll distance between the current scroll position and the target element position.
  5. Use the window.scrollTo() method to smoothly scroll to the target element. You can pass the target element position and some additional options like behavior: 'smooth' to create a smooth scrolling effect.

Here's an example implementation:

// Get all anchor links on the webpage const anchorLinks = document.querySelectorAll('a[href^="#"]'); // Attach click event listener to all anchor links anchorLinks.forEach(anchorLink => { anchorLink.addEventListener('click', smoothScroll); }); // Event handler for smooth scrolling function smoothScroll(event) { // Prevent default anchor link behavior event.preventDefault(); // Get the target element const target = document.querySelector(this.getAttribute('href')); // Calculate the scroll distance const scrollDistance = target.offsetTop - window.pageYOffset; // Scroll smoothly to the target element window.scrollTo({ top: target.offsetTop, behavior: 'smooth' }); }

By adding this JavaScript code to your webpage, all anchor links with href attribute starting with # will scroll smoothly to their target elements.