I saw this article (it is good), and loved the scroll bar at the top showing how far in the article you are:
https://www.404media.co/automattic-buyout-offer-wordpress-matt-mullenweg/
So, I tried to implement that on my WordPress website(s).
Here’s how you can add the scroll progress bar on a XenForo forum. 🙂
Adding countless plugins makes WordPress suck, so custom code using a child theme is the way to go (in my opinion & experience).
First and only in-page advert:
Thank you for your support and understanding.
I added some custom CSS in the child’t heme’s style.css file (though, see the other code further below):
/* BEGIN BikeGremlin progress bar custom CSS */
#scrollProgressBar {
position: fixed;
top: 0;
left: 0;
width: 0%;
height: 9px;
background-color: #9b2fc9; /* Change this color to match your theme */
z-index: 99999;
}
/* END BikeGremlin progress bar custom CSS */
Note:
An alternative, I went with for some sites, is CSS showing a transition from purple to blue, to make it look nicer, so this is what I used on my sites, instead of the above-shown code:
/* BEGIN BikeGremlin progress bar custom CSS */
#scrollProgressBar {
position: fixed;
top: 0;
left: 0;
width: 0%;
height: 9px;
background: linear-gradient(to right, #9b2fc9, #2177c0); /* Transition from purple to blue */
z-index: 99999;
}
/* END BikeGremlin progress bar custom CSS */
Then, I added the following JavaScript to the child theme’s functions.php file, followed with a some PHP :
// BEGIN BikeGremlin progress bar display on top
// Enqueue JavaScript for scroll progress bar using the CSS element defined in style.css
function enqueue_scroll_progress_bar_script() {
echo '<script>
document.addEventListener("scroll", function() {
var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
var docHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
var scrollPercent = (scrollTop / docHeight) * 100;
document.getElementById("scrollProgressBar").style.width = scrollPercent + "%";
});
</script>';
}
add_action('wp_footer', 'enqueue_scroll_progress_bar_script');
// Add the Progress Bar Element to the footer
function add_scroll_progress_bar_element() {
echo '<div id="scrollProgressBar"></div>';
}
add_action('wp_body_open', 'add_scroll_progress_bar_element');
// END BikeGremlin progress bar display on top
Basically:
- The CSS defines the scroll bar and sticks it to the front and to the top.
- JavaScript listens for the scroll event and triggers whenever you scroll.
- PHP hook ads the progress bar HTML right after the opening <body> tag.
That’s it. 🙂
Last updated:
Originally published: