<div class="back-to-top-container back-to-top-container--intersecting" data-controller="viewport-entrance-toggle" data-viewport-entrance-toggle-class="back-to-top-container--intersecting">
  <button class="back-to-top__button button" onclick="window.scrollTo({ top: 0, behavior: 'smooth' })">Back to top</button>
</div>
  
<div class="demo-content"></div>
.back-to-top-container {
  position: absolute;
  top: 0;
  right: 0;
  height: 100vh;
  width: 100vw;
  box-shadow: inset 0 0 0 1rem #cfc;
}

.back-to-top__button {
  position: fixed;
  bottom: 1rem;
  right: 2rem;
  opacity: 1;
  visibility: visible;
  transition: all 0.2s ease;
}

.back-to-top-container--intersecting .back-to-top__button {
  opacity: 0;
  visibility: hidden;
}

.button {
  -webkit-appearance: none;
  background-color: rgba(255,255,255,0.85);
  display: inline-block;
  padding: 0.5em 1em;
  border-radius: 1.5em;
  vertical-align: middle;
  text-align: center;
  cursor: pointer;
  border: 1px solid #555;
  font-size: 1rem;
}

.demo-content {
  max-width: 80vw;
  margin: 2rem auto;
  background-color: #fff;
  height: 4000px;
}

html, body {
  background-color: #ccc;
  text-align: center;
}
const application = Stimulus.Application.start()

application.register("viewport-entrance-toggle", class extends Stimulus.Controller {

  initialize() {
    this.intersectionObserver = new IntersectionObserver(entries => this.processIntersectionEntries(entries))
  }

  connect() {
    this.intersectionObserver.observe(this.element)
  }

  disconnect() {
    this.intersectionObserver.unobserve(this.element)
  }

  // Private

  processIntersectionEntries(entries) {
    entries.forEach(entry => {
      this.element.classList.toggle(this.data.get("class"), entry.isIntersecting)
    })
  }
})
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://unpkg.com/stimulus/dist/stimulus.umd.js
  2. https://unpkg.com/smoothscroll-polyfill@0.4.3/dist/smoothscroll.min.js