Theme & Front End JavaScript Beginner

Show a Reading Progress Bar

Add a thin bar across the top of the screen that fills up as the reader scrolls through an article.

Tested on WordPress 7.1 No plugin needed Updated
script.js 22 lines
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();
} );

Where to add this

Recommended A code snippets plugin As a JavaScript snippet set to load in the footer.
Child theme Save it as a .js file and load it with wp_enqueue_script() from functions.php.
Page builder Your builder's custom code area, set to load in the footer.

On long articles, a progress bar tells readers how far through they are and how much is left, which encourages them to finish.

How it works

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.

Things to watch

  • Pages without an <article> element, like most archives, don’t get a bar.
  • If you have a sticky header, change top:0 to sit below it.

How to test 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.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only