How to add Scroll Percentage to WordPress without any plugin

In this guide I will be adding a scroll percentage to a WordPress page. For a working demo please check this page.

First step is to add the HTML code that will display the scroll percentage number inside the page or theme header. in this example I’m adding it to a single post and for that I use the HTML gutenberg block.

code:

<p id="scrollPercentLabel">Scroll Percentage: <span>0</span>%</p>

For the working part we need to include the following JS code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>


<script>
$(document).ready(function() {

				$(window).scroll(function(e){
					var scrollTop = $(window).scrollTop();
					var docHeight = $(document).height();
					var winHeight = $(window).height();
					var scrollPercent = (scrollTop) / (docHeight - winHeight);
					var scrollPercentRounded = Math.round(scrollPercent*100);

				    $('#scrollPercentLabel>span').html(scrollPercentRounded);
				    repositionLabel();
				});
	   
				$(window).resize(function(){
					repositionLabel();
				});

				function repositionLabel() {
					$('#scrollPercentLabel').css({
						position:'fixed',
						left: ($(window).width() - $('#scrollPercentLabel').outerWidth()) / 2,
						top: (($(window).height() - $('#scrollPercentLabel').outerHeight()) / 2) - $('#scrollPercentLabel').height()
					});
				}

				repositionLabel();

			});

</script>

This script uses an older version of jQuery than WordPress, which could create issues if your theme uses some of the newer features.
So, when you’ve included this code, double-check that everything is working on your website.

To add this code to your website you can either edit the functions.php file of your active theme or use a plugin such as Insert Headers and Footers.


This step is optional and use it only if you want to add custom style to the Scroll Percentage text, for example to change it from this:

to this:
This image has an empty alt attribute; its file name is image-16.png

use the following css code:

#scrollPercentLabel {
	font-family: Impact;
	font-size: 50px;
	color: #2B2B2B;
	background: rgba(255, 255, 255, 0.5);
	padding: 20px;
	position: absolute;
	top: 50%;
	left: 50%;
	box-shadow: 8px 8px 5px rgba(20, 20, 20, 1);
	border-radius: 15px;
	}

The easiest way to add css in WordPress is the built-in Customizer > Additional CSS

Was this post helpful?

Leave a Comment