Scroll to top

Edit on Github
Open in Playground

Introduction

amp-position-observer combined with amp-animation can be used to implement a scroll to top button. This pattern is often used in e-commerce pages where the user has to scroll through a long list of items.

Setup

Import amp-position-observer extension

<script async custom-element="amp-position-observer" src="https://cdn.ampproject.org/v0/amp-position-observer-0.1.js"></script>

Import amp-animation extension

<script async custom-element="amp-animation" src="https://cdn.ampproject.org/v0/amp-animation-0.1.js"></script>

Styles

The CSS used for these samples are included here for reference.

These rules are simply needed to make the samples work but are not fundamental to the concepts covered here.

<style amp-custom>

  .scrollToTop {
    color: #fafafa;
    font-size: 1.4em;
    box-shadow: 0 1px 1.5px 0 rgba(0,0,0,.12), 0 1px 1px 0 rgba(0,0,0,.24);
    width: 50px;
    height: 50px;
    border-radius: 100px;
    border: none;
    outline: none;
    background: #E91E63;
    z-index: 9999;
    bottom: 10px;
    right: 10px;
    position: fixed;
    opacity: 0;
    visibility: hidden;
  }
  #marker {
    position: absolute;
    top: 100px;
    width: 0px;
    height: 0px;
  }
</style>

Scroll to top

We use 2 amp-animation elements to trigger the visibility of the button. The first one is for making the button visible...

Example

<amp-animation id="showAnim"
  layout="nodisplay">
  <script type="application/json">
    {
      "duration": "200ms",
      "fill": "both",
      "iterations": "1",
      "direction": "alternate",
      "animations": [{
        "selector": "#scrollToTopButton",
        "keyframes": [{
          "opacity": "1",
          "visibility": "visible"
        }]
      }]
    }
  </script>
</amp-animation>

... and the second one is for adding the button.

Example

<amp-animation id="hideAnim"
  layout="nodisplay">
  <script type="application/json">
    {
      "duration": "200ms",
      "fill": "both",
      "iterations": "1",
      "direction": "alternate",
      "animations": [{
        "selector": "#scrollToTopButton",
        "keyframes": [{
          "opacity": "0",
          "visibility": "hidden"
        }]
      }]
    }
  </script>
</amp-animation>

We use amp-position-observer to start the animation when the user starts to scroll.

Example

<div id="marker">
  <amp-position-observer on="enter:hideAnim.start; exit:showAnim.start"
    layout="nodisplay">
  </amp-position-observer>
</div>

We use the scrollTo action to scroll the page when the button is tapped. Find more about actions here.

Example

<button id="scrollToTopButton"
  on="tap:top-header.scrollTo(duration=200)"
  class="scrollToTop"></button>