scroll to smooth javascript

Scroll to Smooth JavaScript

If you want to make your website look more professional and polished, adding smooth scrolling can be a great way to improve user experience. The default scroll is jerky and choppy, but a smooth scroll can make your website feel more refined.

Using jQuery

One way to achieve smooth scrolling is by using jQuery. Here's an example code snippet:


  $('a[href*="#"]')
  .not('[href="#"]')
  .not('[href="#0"]')
  .click(function(event) {
      if (
          location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
          &&
          location.hostname == this.hostname
      ) {
          var target = $(this.hash);
          target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
          if (target.length) {
              event.preventDefault();
              $('html, body').animate({
                  scrollTop: (target.offset().top - 100)
              }, 1000, function() {
                  var $target = $(target);
                  $target.focus();
                  if ($target.is(":focus")) {
                      return false;
                  } else {
                      $target.attr('tabindex','-1');
                      $target.focus();
                  };
              });
          }
      }
  });

This code works by selecting all anchor tags with a href attribute containing the "#" symbol. It then excludes any links with a "#" or "#0" href as they usually don't have any content. Finally, it animates the scroll to the target element over a duration of 1000ms (1 second). You can adjust this duration to your liking.

Using Vanilla JavaScript

If you prefer not to use jQuery, you can achieve the same effect with vanilla JavaScript. Here's an example:


  document.querySelectorAll('a[href^="#"]').forEach(anchor => {
      anchor.addEventListener('click', function (e) {
          e.preventDefault();
  
          document.querySelector(this.getAttribute('href')).scrollIntoView({
              behavior: 'smooth'
          });
      });
  });

This code works by selecting all anchor tags with a href attribute starting with the "#" symbol. It adds a click event listener to each of them, which prevents the default behavior of jumping to the element with the corresponding id. Instead, it smoothly scrolls to the target element using the scrollIntoView method with the behavior option set to "smooth".

Conclusion

Both of these methods are effective ways of achieving smooth scrolling on your website. It's up to you to decide which one you're more comfortable with. You can further customize these codes based on your specific needs and preferences.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe