Skip to content

Commit

Permalink
Add scroll progress bar
Browse files Browse the repository at this point in the history
  • Loading branch information
Chalarangelo committed May 24, 2021
1 parent 23bff9b commit 407ad20
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions snippets/scroll-progress-bar.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
---
title: Scroll progress bar
tags: animation,visual,intermediate
---

Creates a progress bar indicating the scroll percentage of the page.

- Use `position: fixed` and a large `z-index` value to place the element at the top of the page and above any content.
- Use `EventTarget.addEventListener()` along with `Element.scrollTop` to determine the scroll percentage of the document and apply it to the `width` of the element.

```html
<div id="scroll-progress"></div>
```

```css
body {
min-height: 200vh;
}

#scroll-progress {
position: fixed;
top: 0;
width: 0%;
height: 4px;
background: #7983ff;
z-index: 10000;
}
```

```js
const scrollProgress = document.getElementById('scroll-progress');
const height =
document.documentElement.scrollHeight - document.documentElement.clientHeight;

window.addEventListener('scroll', () => {
const scrollTop =
document.body.scrollTop || document.documentElement.scrollTop;
scrollProgress.style.width = `${(scrollTop / height) * 100}%`;
});
```

0 comments on commit 407ad20

Please sign in to comment.