-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReadingProgress.astro
More file actions
40 lines (33 loc) · 1.39 KB
/
Copy pathReadingProgress.astro
File metadata and controls
40 lines (33 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
---
// Reading progress bar component - shows scroll progress
---
<div id="reading-progress" class="reading-progress" aria-hidden="true"></div>
<script>
const progressBar = document.getElementById('reading-progress');
const article = document.getElementById('article-content');
if (progressBar && article) {
const updateProgress = () => {
const rect = article.getBoundingClientRect();
const articleTop = rect.top + window.scrollY;
const articleHeight = rect.height;
const windowHeight = window.innerHeight;
const scrollY = window.scrollY;
// Calculate the total scrollable distance from the top of the page
// to the point where the bottom of the article reaches the bottom of the viewport.
const scrollRange = articleTop + articleHeight - windowHeight;
let progress = 0;
if (scrollRange > 0) {
// Start at 0% when the page is at the top (scrollY = 0)
// and reach 100% at the end of the article.
progress = Math.max(0, Math.min(100, (scrollY / scrollRange) * 100));
} else {
// If the article is already fully visible, progress is 100%.
progress = 100;
}
progressBar.style.width = `${progress}%`;
};
window.addEventListener('scroll', updateProgress, { passive: true });
window.addEventListener('resize', updateProgress, { passive: true });
updateProgress();
}
</script>