惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
The GitHub Blog
The GitHub Blog
J
Java Code Geeks
Engineering at Meta
Engineering at Meta
N
Netflix TechBlog - Medium
A
About on SuperTechFans
博客园 - 三生石上(FineUI控件)
罗磊的独立博客
MongoDB | Blog
MongoDB | Blog
B
Blog RSS Feed
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
有赞技术团队
有赞技术团队
T
Tailwind CSS Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Vercel News
Vercel News
腾讯CDC
博客园 - 聂微东
The Cloudflare Blog
F
Fortinet All Blogs
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
Visual Studio Blog
Last Week in AI
Last Week in AI
B
Blog

Example blog

Ghost routing explained with routes.yaml examples — routes, collections & taxonomies Ghost redirects explained with practical redirects.yaml examples How to Serve JSON or XML Data in Ghost How to Change Your Default Post Template in Ghost Ghost Custom Theme Settings How to add Google Fonts to Ghost Themes How to Configure Ghost with Mailgun Ghost Theme Structure & Organization How to Make Custom Templates in Ghost Themes How to Install Ghost CMS via Ghost-CLI How to Add Syntax Highlighting to Ghost The best Ghost CMS hosting platforms Ghost 6.0 — Social Web and Native Ghost Analytics Ghost CMS Social web beta, email 2FA and more author social links How to keep custom design settings when updating your Ghost theme How to use the public preview card in Ghost How to add members-specific sections in Ghost How to customize the default content CTA in Ghost How to build a custom homepage in Ghost An overview of Ghost editor cards and and how they work Ghost CMS News: One-time payments & collecting sales tax How to customize the private site access template in Ghost How to add custom fonts in Ghost themes Ghost CMS News: Additional payment methods & internal linking How to use Code Injection in Ghost How to set meta data of your custom routes & collections in Ghost Ghost CMS News: TK reminders, ActivityPub and improvements How to format dates and use the date helper in Ghost Ghost CMS internationalization, custom fonts & spam protection Understanding and optimizing post and page settings in Ghost CMS
How to Add a Scroll Top & Progress Indicator Button in Ghost
Bright Themes · 2022-06-26 · via Example blog

When your page is very long you may want to give your users an option to quickly scroll back to the top of the page. In such cases, the best solution is to add a button that will appear after the user scrolls a specified number of pixels.

These buttons usually float in the bottom corner of sites and then take you back to the top of the page when clicked. They are pretty easy to create with JavaScript, we just have to look out to make it non-obtrusive while still being a large enough target to tap or click.

We will start simple, then extend it with additional functionality, like tracking the scroll progress and indicating it on the button.

Here is the button markup with an arrow pointing up inside:

<button
  class="btn-toggle-round scroll-top js-scroll-top"
  type="button"
  title="Scroll to top"
>
  <svg
    xmlns="http://www.w3.org/2000/svg"
    class="icon icon-tabler icon-tabler-arrow-up"
    width="24"
    height="24"
    viewBox="0 0 24 24"
    stroke-width=""
    stroke="cuurentColor"
    fill="none"
    stroke-linecap="round"
    stroke-linejoin="round"
  >
    <path stroke="none" d="M0 0h24v24H0z" fill="none" />
    <line x1="12" y1="5" x2="12" y2="19" />
    <line x1="18" y1="11" x2="12" y2="5" />
    <line x1="6" y1="11" x2="12" y2="5" />
  </svg>
</button>

Styling the button:

.scroll-top {
  position: fixed;
  z-index: 50;
  padding: 0;
  right: 20px;
  bottom: 20px;
  opacity: 1;
  visibility: visible;
  transform: translateY(0px);
  height: 46px;
  width: 46px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.4s ease;
  border: none;
  box-shadow: inset 0 0 0 2px #ccc;
  color: #ccc;
  background-color: #fff;
}

.scroll-top .icon-tabler-arrow-up {
  position: absolute;
  stroke-width: 2px;
  stroke: #333;
}

.scroll-top:hover {
  color: var(--ghost-accent-color);
}

.scroll-top:hover .icon-tabler-arrow-up {
  stroke: var(--ghost-accent-color);
}

The above CSS will make the scroll top button fixed at the bottom right corner of the page, you can easily adjust the position, colors, or anything else.

Now, to make the button functional, we need a bit of javascript, which can be added to the button ( onclick event) or separately from Code Injection:

const scrollTopBtn = document.querySelector('.js-scroll-top');
if (scrollTopBtn) {
  scrollTopBtn.onclick = () => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };
}

We have the basic functionality and styling, now let's see how we can improve it.

Animating the button visibility

You probably wouldn't want the button to be visible by default, as when you are at the top of the page, you don't need to scroll up. So let's improve this and make the bottom visible only after a certain amount of scroll.

For this we need to track the scroll event and change the scroll top button:

const offset = 100;
window.addEventListener(
  'scroll',
  function (event) {
    //Scroll back to top when offset is met
    const scrollPos =
      window.scrollY ||
      window.scrollTop ||
      document.getElementsByTagName('html')[0].scrollTop;
    scrollPos > offset
      ? scrollTop.classList.add('is-active')
      : scrollTop.classList.remove('is-active');
  },
  false,
);

This will add the .is-active class to the button, which we can use to modify the style and animate the button:

.scroll-top {
  opacity: 0;
  visibility: hidden;
  transform: translateY(15px);
}

.scroll-top.is-active {
  opacity: 1;
  visibility: visible;
  transform: translateY(0);
}

Great, now let's see what else we can improve. An interesting and useful feature we can add is to make the button a progress indicator at the same time.

Add progress indicator function

To achieve this, we need to extend the markup and add the following inside the <button>:

<svg class="progress-circle" width="100%" height="100%" viewBox="-1 -1 102 102">
  <path d="M50,1 a49,49 0 0,1 0,98 a49,49 0 0,1 0,-98" />
</svg>

We'll use this progress circle SVG to highlight the scroll status, for this we need to calculate the percent of the scroll using javascript:

const progressPath = document.querySelector('.scroll-top path');
const pathLength = progressPath.getTotalLength();
progressPath.style.transition = progressPath.style.WebkitTransition = 'none';
progressPath.style.strokeDasharray = `${pathLength} ${pathLength}`;
progressPath.style.strokeDashoffset = pathLength;
progressPath.getBoundingClientRect();
progressPath.style.transition = progressPath.style.WebkitTransition = 'stroke-dashoffset 10ms linear';
const updateProgress = function() {
  const scroll = window.scrollY || window.scrollTopBtn || document.documentElement.scrollTopBtn;

  const docHeight = Math.max(
    document.body.scrollHeight, document.documentElement.scrollHeight,
    document.body.offsetHeight, document.documentElement.offsetHeight,
    document.body.clientHeight, document.documentElement.clientHeight
  );

  const windowHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);

  const height = docHeight - windowHeight;
  var progress = pathLength - (scroll * pathLength / height);
  progressPath.style.strokeDashoffset = progress;
}

window.addEventListener('scroll', function(event) {
  updateProgress();
}

Of course, some additional CSS is needed to make all of this work:

.scroll-top svg path {
  fill: none;
}

.scroll-top svg.progress-circle path {
  stroke: #333;
  stroke-width: 4;
  transition: all 0.4s ease;
}

.scroll-top:hover .progress-circle path {
  stroke: var(--ghost-accent-color);
}

Now we have everything, a scroll top function that also acts as a progress indicator. Check out the whole code, and see it in action: https://codepen.io/nhunyadi/pen/zYWOKyo