How to make "Back To Top" functionality with own theme in five minutes

24 Feb.2020
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.

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.

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.