Users usually wonder how much more is left for reading? A percentage scrolled indicator can be used for providing the percentage of page left for reading and it increases the overall user experience. In this post I will provide the easiest way to create a percentage scrolled indicator.
View Demo
For creating a percentage scrolled indicator we need to learn the following JavaScript properties and DOM events:
- window.pageYOffset and Element.offsetHeight : Refer this article to learn these two properties.
- window.innerHeight: This property is set to the height of the viewport(HTML tag). Similarly window.innerWidth returns the width of the viewport.
- onscroll Event: This event is triggered when the viewport(HTML tag) scrollbar is scrolled.
Implementation Of Percentage Scrolled Indicator
Here is the logic for calculating the percentage scrolled
Here is the code for calculating the percentage scrolled.
<!doctype html>
<html>
<head>
<title>Color Changing</title>
<style type="text/css">
#percentage
{
position: fixed;
}
</style>
</head>
<body>
<div id="percentage"></div>
<div style="height: 4000px;"></div>
</body>
<script type="text/javascript">
window.onscroll = function(){
var heightOfWindow = window.innerHeight;
var contentScrolled = window.pageYOffset;
var bodyHeight = window.document.getElementsByTagName("body")[0].offsetHeight;
if(bodyHeight - contentScrolled <= heightOfWindow)
{
window.document.getElementById("percentage").innerHTML = "100%";
}
else
{
var total = bodyHeight - heightOfWindow;
var got = contentScrolled;
window.document.getElementById("percentage").innerHTML = parseInt((got/total) * 100);
}
}
</script>
</html>
<html>
<head>
<title>Color Changing</title>
<style type="text/css">
#percentage
{
position: fixed;
}
</style>
</head>
<body>
<div id="percentage"></div>
<div style="height: 4000px;"></div>
</body>
<script type="text/javascript">
window.onscroll = function(){
var heightOfWindow = window.innerHeight;
var contentScrolled = window.pageYOffset;
var bodyHeight = window.document.getElementsByTagName("body")[0].offsetHeight;
if(bodyHeight - contentScrolled <= heightOfWindow)
{
window.document.getElementById("percentage").innerHTML = "100%";
}
else
{
var total = bodyHeight - heightOfWindow;
var got = contentScrolled;
window.document.getElementById("percentage").innerHTML = parseInt((got/total) * 100);
}
}
</script>
</html>