Build a Reading Progress Bar in Drupal with JavaScript
A reading progress bar is the slim horizontal strip that appears at the top of the browser window and fills as you move down a page. You have probably seen one on an Australian news site while working through a long election explainer, or on a university research article before scrolling to the references. It gives an instant indication of how much text remains, which stops people abandoning a piece halfway through because they assume it runs on forever.
For Drupal, the widget is a front-end nicety rather than a content-modelling challenge. The structure of your article, node or custom entity is already handled by views and templates; what the bar needs is a small script that measures scroll depth, an element to draw into, and a tidy way of attaching both to the page. Drupal's library system handles that attachment cleanly, and the whole thing can run in vanilla JavaScript without pulling in jQuery or installing a contributed module.
What follows is a working approach: attaching the script, calculating the percentage, styling the result, handling the quirks Drupal introduces through Ajax and BigPipe, and a set of checks to run before you publish. A comparison of alternative techniques sits near the end so you can choose one that suits your stack instead of copying a snippet that fights the theme.
Why Australian Drupal sites benefit from a progress cue
Long-form content fills the Australian market: council agendas, hospital and emergency-services announcements, recipe features, academic papers, and the endless listicles that publishers in Melbourne and Sydney produce every week. Plenty of it gets read on a phone during a tram or train commute, where a quick visual cue often decides whether a reader finishes an article or bounces straight back to a search result.
Local habits also shape how you label and comment the feature. Australian editorial teams use British spelling, so "colour", "behaviour" and "organise" belong in your class names, commit messages and code comments when the same people maintain the theme. Teams in Perth and Ballarat tend to keep issue trackers informal — "keen to ship this arvo" — so a lean, dependency-free implementation suits that tone better than a heavyweight plugin with its own settings screen.
There is a commercial reason as well. Australian councils, universities and not-for-profits in Canberra, Darwin and Hobart often settle on Drupal because government procurement rules demand WCAG 2.1 AA accessibility and strict change control. A progress indicator that behaves predictably for screen reader users, that respects a visitor's reduced-motion preference, and that never blocks the page is exactly the sort of detail that earns goodwill in an accessibility audit.
Attaching the script through Drupal's library system
Start by creating a custom module called reading_progress with a js/reading-progress.js file and a reading_progress.libraries.yml manifest. Declaring the asset in YAML keeps it reusable across themes and lets Drupal cache it aggressively in production.
reading_progress:
version: 1.x
js:
js/reading-progress.js: {}
css:
component:
css/reading-progress.css: {}
Attach the library and pass configuration through drupalSettings, which Drupal serialises into the page as a JSON object:
function reading_progress_preprocess_html(&$variables) {
$variables['#attached']['library'][] = 'reading_progress/reading_progress';
$variables['#attached']['drupalSettings']['readingProgress'] = [
'target' => '#reading-progress .reading-progress__bar',
'offset' => 0,
];
}
Because drupalSettings is data rather than code, you can override the target selector, the offset used when a sticky header covers the top of the article, and even the accent colour per content type. If your feature needs to react to entity saves, form submissions or node updates rather than simply rendering the bar, the Drupal hooks guide covers how hook invocation works and where to register listeners.
Calculating the scroll position in vanilla JavaScript
The maths is straightforward. Take the scrollable distance of the document, divide the current scroll offset by it, and clamp the result between zero and one. The trick is doing that calculation without flooding the main thread, so the scroll listener stays passive and the work happens inside requestAnimationFrame.
(function (Drupal, drupalSettings) {
'use strict';
const config = Object.assign({
target: '#reading-progress .reading-progress__bar',
offset: 0,
}, drupalSettings.readingProgress || {});
const bar = document.querySelector(config.target);
if (!bar) { return; }
let ticking = false;
function documentHeight() {
return Math.max(
document.body.scrollHeight,
document.documentElement.scrollHeight,
document.body.offsetHeight,
document.documentElement.offsetHeight,
document.documentElement.clientHeight
);
}
function update() {
const scrollable = documentHeight() - window.innerHeight;
const scrolled = window.scrollY + config.offset;
const ratio = scrollable > 0
? Math.min(Math.max(scrolled / scrollable, 0), 1)
: 1;
bar.style.setProperty('--progress', ratio.toFixed(4));
ticking = false;
}
function requestUpdate() {
if (!ticking) {
ticking = true;
window.requestAnimationFrame(update);
}
}
window.addEventListener('scroll', requestUpdate, { passive: true });
window.addEventListener('resize', requestUpdate);
document.addEventListener('DOMContentLoaded', requestUpdate);
})(Drupal, drupalSettings);
Two edge cases deserve attention. When a page is shorter than the viewport there is nothing to scroll, so the ratio resolves to one and the bar fills immediately. When the browser restores a previous scroll position on reload, the initial render can show an empty bar until the first scroll event fires, which is why the DOMContentLoaded call in the snippet matters. On mobile, window.innerHeight shrinks as browser chrome hides, so recompute on resize rather than trusting the value captured at load.
Styling the bar with CSS custom properties
The markup is deliberately plain: one wrapper for the track and one inner element for the fill. Keeping the fill as an empty span avoids reflow-heavy layout and lets CSS handle the width entirely.
<div class="reading-progress" aria-hidden="true">
<span class="reading-progress__bar"></span>
</div>
.reading-progress {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 4px;
z-index: 1000;
background: var(--color-gray-100, #e6e6e6);
}
.reading-progress__bar {
display: block;
height: 100%;
width: calc(var(--progress, 0) * 100%);
background: var(--color-blue-700, #0a5aa5);
transition: width 80ms linear;
}
@media (prefers-reduced-motion: reduce) {
.reading-progress__bar { transition: none; }
}
Because the fill width is driven by a single custom property, retuning the animation is a one-line change, and a theme can swap the palette without touching JavaScript. Claro-based themes expose a palette of CSS custom properties such as the blue and grey shades above, and many Australian agency themes layer their own brand tokens on top, so check the theme's variables.css before hard-coding a hex value. If your site uses a sticky navigation bar, add the header's height to the offset setting so the percentage matches the text the reader can actually see.
Keeping the bar smooth on Ajax and heavy third-party pages
Drupal's Ajax framework swaps page fragments without a full reload, which invalidates any scroll measurement cached earlier. When an infinite scroll pager or a view with AJAX loaders is in play, recalculate after the replacement finishes by listening for Drupal's Ajax completion behaviour, or attach a MutationObserver to the article container that triggers an update when its height changes.
Page weight matters just as much. Aggregation and affiliate pages often carry scripts that compete for the main thread — a casino review page, for example, pulls in ad networks, tracking pixels and lazy banners that can stall for seconds on a busy connection. That is precisely where a scroll-driven animation stutters, so keep the calculation cheap, avoid layout reads inside the scroll handler and make sure your CSS transitions do not trigger repaints of surrounding content. For regional and remote Australian audiences on slower NBN services, a lightweight script that degrades to a static bar is kinder than a jQuery plugin that ships an extra library for one decorative element.
Accessibility, testing and a pre-publish checklist
Treat the indicator as decorative unless it carries meaning. If the bar is purely a visual cue, mark the wrapper aria-hidden="true" so screen readers ignore it, and never let it become focusable. If it communicates genuine state, use role="progressbar" with aria-valuemin, aria-valuemax and a periodically updated aria-valuenow instead. Keyboard users gain more from a skip link to the end of the article than from a progress strip, so offer both. Test with reduced motion enabled, with JavaScript disabled, and with a keyboard only.
Weighing the options side by side helps you choose the right technique for the content type you are serving:
| Approach | Browser support | Effort | Best suited to |
|---|---|---|---|
| Scroll listener with requestAnimationFrame | All modern browsers | Low | Themes that also show the bar on Ajax-loaded content |
| IntersectionObserver sentinels | Chrome, Edge, Firefox, Safari 16.4+ | Medium | Very long, chaptered articles with clear section boundaries |
| CSS scroll-driven animation | Chrome and Edge only | Low | Progressive enhancement with a fallback for other browsers |
| Server-rendered percentage | Universal | Medium | Pages exported as static HTML or printed to PDF |
Run through these before the release goes live:
Drupal-side checks
- The library is declared in a
.libraries.ymlfile and attached through#attached, not hard-coded in a template drupalSettingscarries the selector, offset and colour rather than inline script tags- The bar markup sits in the base template so every paginated view includes it
- Ajax and BigPipe responses recalculate the scroll height correctly
Browser-side checks
- The bar reaches 100 percent on short pages and stays there on long ones
prefers-reduced-motionremoves the transition without hiding the indicator- The fill uses
transformor a custom property instead of animating layout properties - Resizing the window, rotating a phone and restoring a previous scroll position all behave
Once the script is attached through the library system and the bar responds to real scroll positions, the feature stays in the theme's hands rather than in a contributed module's update path. Australian Drupal teams tend to keep maintenance overhead low, and a four-pixel strip built from a dozen lines of JavaScript is about as cheap as it gets.