24 Feb.2020

Drupal (any version): How to make "Back To Top" functionality with own theme in five minutes

Scroll To Top / Back To Top

Very often when developing or maintaining a site, clients ask me to create functionality in the footer that will scroll the page to the top.

I know this can be done with the helpful and wonderful Back To Top module, but I am the person who tries to have as few enabled contrib modules as possible on the site and save time on support in case a new version of the module appears.

Below I will show how to make similar functionality in 5 minutes.

Drupal 8 or 9.

File
script.js
  /**
   * Back to Top scrolling.
   *
   * @type {{attach: Drupal.behaviors.backToTop.attach}}
   */
  Drupal.behaviors.backToTop = {
    attach: function (context, settings) {
      $('.back-to-top', context).once('upperBehavior').on('click', function (event) {
        event.preventDefault();
        $('html, body', context).animate({scrollTop: 0}, 500);
        return false;
      });
    }
  };

This piece of code can be added to a custom theme or your own custom module.

File
page.html.twig
<a href="#" class="back-to-top"><i class="fas fa-arrow-circle-up"></i></a>

On the front-end just enough to create a custom block or add the following or similar code to the theme. My example uses the FontAwesome icon, however, you can use which you prefer. Currency, no styles are shown, feel free to experiment with the design of the link/button.

Drupal 10.

File
script.js
  /**
   * Back to Top scrolling.
   *
   * @type {{attach: Drupal.behaviors.backToTop.attach}}
   */
  Drupal.behaviors.backToTop = {
    attach: function (context, settings) {
      once('upperBehavior', '.back-to-top', context).forEach((upper) => {
        $(upper).on('click', function (event) {
          event.preventDefault();
          $('html, body', context).animate({ scrollTop: 0 }, 500);
          return false;
        });
      });
    },
  };

Drupal 10 another solution.

File
script.js
  /**
   * Back to Top scrolling.
   *
   * @type {{attach: Drupal.behaviors.backToTop.attach}}
   */
  Drupal.behaviors.backToTop = {
    attach: function (context, settings) {
      $(once('upperBehavior', '.scroll-top', context))
        .on('click', function (event) {
          event.preventDefault();
          $('html, body', context).animate({scrollTop: 0}, 'slow');
          return false;
        });
    }
  };
Conclusion

As you can see, it quickly and easy. I hope this short article will be helpful to someone. It is not necessary to use 500 simple modules per site (yes, I have met such sites). Good luck and have a great time.

Ruslan Piskarov

Ukraine
PHP/WEB Developer / Drupal Expert. More than 11 years of experience delivering Drupal based General Purpose solutions for different sectors such as Job Boards, Product Portfolios, Geo Coding, Real Estate solutions, E-Commerce, Classifieds, Corporate and online Magazines/Newspapers.