Add a thin bar across the top of the screen that fills up as the reader scrolls through an article.
document.addEventListener( 'DOMContentLoaded', () => {
const article = document.querySelector( 'article' );
if ( ! article ) {
return;
}
const bar = document.createElement( 'div' );
bar.setAttribute( 'aria-hidden', 'true' );
bar.style.cssText = 'position:fixed;top:0;left:0;z-index:99999;height:3px;width:0;background:#6F58CA;transition:width .1s linear';
document.body.appendChild( bar );
const update = () => {
const rect = article.getBoundingClientRect();
const total = rect.height - window.innerHeight;
const done = total > 0 ? Math.min( Math.max( -rect.top / total, 0 ), 1 ) : 1;
bar.style.width = ( done * 100 ) + '%';
};
window.addEventListener( 'scroll', update, { passive: true } );
window.addEventListener( 'resize', update );
update();
} );
On long articles, a progress bar tells readers how far through they are and how much is left, which encourages them to finish.
The script adds a fixed 3-pixel bar to the top of the window. As the reader scrolls, it measures how much of the <article> element has passed the top of the screen and sets the bar’s width to match. It measures the article rather than the whole page, so comments and footer don’t count.
The bar is hidden from screen readers, since it’s purely visual.
<article> element, like most archives, don’t get a bar.top:0 to sit below it.Open a long post and scroll. The purple bar at the top should grow and reach the full width at the end of the article.