Skip to content
the poor coder

scroll to smooth javascript

Poor Man
Published
Reading time
2 min read
On this page

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:

Text

  $('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:

Text

  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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC