From 407ad2043496dc34a2e5126248ec300c4352ad6d Mon Sep 17 00:00:00 2001 From: Chalarangelo Date: Mon, 24 May 2021 09:42:03 +0300 Subject: [PATCH] Add scroll progress bar --- snippets/scroll-progress-bar.md | 40 +++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 snippets/scroll-progress-bar.md diff --git a/snippets/scroll-progress-bar.md b/snippets/scroll-progress-bar.md new file mode 100644 index 000000000..9e27590b1 --- /dev/null +++ b/snippets/scroll-progress-bar.md @@ -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 +
+``` + +```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}%`; +}); +```