Giving a whole new look to my personal website I wanted to add a Youtube-like progress bar on top of my posts for a better reader experience.
That’s what it looks like :
It’s easily and fully customizable and it only takes :
- 1 HTML element
- 1 CSS block (6 simple properties)
- 12 Vanilla JS lines
Let’s do it !
First, you need an HTML node to display your progress bar :
Then, you need to customize it with CSS :
Comments are not enough so I will explain:
Line 6 :Retrieve how much the user has scrolled down.
Line 9 :Look at this picture and at the explanation below it.
You want the progress bar to be filled entirely when the user has reached the bottom part of your long content.
It means that the
scroll value must be equal to :
y position of the content +
height of the content –
Line 12:I use
Math.min(x, 100)to ensure
widthdoesn’t go beyond 100% and I use
Math.ceil()to strip the decimal part.
Here is a working pen :
Before making my own progress bar I tried several libraries but I found they were just too much for my need.
Yet I believe that my approach has advantages :
- No dependencies and no HTTP requests made.
- Vanilla JS performances.
- Ultra-tiny and lightweight code + very easy to integrate anywhere.
- Easy to extend with CSS animations.
- Cross-browser compatible.
Thanks for reading
My latest article has reached 10k+ readers and 650+ claps on Medium and I am more than grateful for everything it brought.
Thanks to those who read, clap, share and translate 💖
Like always, I’m opened to suggestions and ideas.
Feel free to reach out at email@example.com ☕
Fullstack Developer, Trainer & Entrepreneur.
Learning stuff, sharing knowledge and building on top of great ideas are my top priorities.