Hacker News new | past | comments | ask | show | jobs | submit login

This is what I use right now for cross-browser smooth scrolling. It's native first with a jQuery fallback.

  <style>
      html, body {
          scroll-behavior: smooth;
      }
  </style>

  <script>
      // Uses native smooth scrolling if available, otherwise uses a jQuery fallback
      // Just add data-scroll attribute to any anchor you want to make smooth
      // Add data-scroll-header to a sticky nav / header to offset the window top
      if (!('scrollBehavior' in document.documentElement.style)) {
          // jQuery fallback
          // Taken from https://css-tricks.com/snippets/jquery/smooth-scrolling/
          $('[data-scroll]').click(function() {
              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) {
                      $('html, body').animate({
                          scrollTop: target.offset().top - $('[data-scroll-header]').height()
                      }, 600);
                      return false;
                  }
              }
          });
      }
  </script>



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: