The Scroll Progress widget offers a simple yet powerful way to enhance your Ghost CMS site by providing readers with a visual cue of their progress through an article. Follow the steps below to add the scroll progress widget to your Ghost CMS website using Ghost code injection.
Scroll progress widget markup and functions
<progress value="0" max="100" data-progress-bar></progress>
<script>
function getScrollPercent() {
const h = document.documentElement,
b = document.body,
st = 'scrollTop',
sh = 'scrollHeight';
return Math.round((h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100);
}
const progressBar = document.querySelector('[data-progress-bar]');
if (progressBar) {
progressBar.setAttribute('value', getScrollPercent());
window.addEventListener('scroll', () => {
progressBar.setAttribute('value', getScrollPercent());
});
}
</script>
First the <progress>
HTML element is used for the progress bar. Additionally
the getScrollPercent()
function will return the actual scroll percent based on
how much the user has scrolled. This is used at the initial load of the page, and
it's also tied to the scroll event.
Scroll progress widget styles
<style>
[data-progress-bar] {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
position:fixed;
top:0;
width:100%;
height:5px;
background-color:transparent;
z-index:1100;
}
[data-progress-bar]::-webkit-progress-bar { background: transparent; }
[data-progress-bar]::-moz-progress-bar { background: var(--ghost-accent-color); }
[data-progress-bar]::-webkit-progress-value { background: var(--ghost-accent-color); }
</style>
The styles are provided using the data attribute data-progress-bar
and fist we
reset the appearance then provide the base style, like height, width and positioning.
Additionally, there are some browser-specific styles.
Scroll progress demo