Scroll events

Whenever an element is scrolled, a "scroll" event fires on it.

Below example displays a progress bar in the top-right corner of the document and updates it as you scroll down.

<style>
.progress{
	 border:1pxsolidblue;
	 width:100px;
	 position:fixed;
	 top:10px;
	right:10px;
}
 .progress>
div{
	 height:12px;
	 background:blue;
	 width:0%;
}
 body{
	 height:2000px;
}
 </style>


<div class="progress"><div></div></div>
<p>Scrollme...</p>

<script>
var bar = document.querySelector(".progressdiv");
addEventListener("scroll", function() {
    var max = document.body.scrollHeight - innerHeight;
    var percent = (pageYOffset / max) * 100;
    bar.style.width = percent + "%";
});
</script >

To make progress bar always stay on top, add the outer element position as fixed which prevents it from scrolling along with the rest of the document. Inside add another element which is dynamically sized relative to the whole bar with % to indicate the current progress.

To get maximum scroll position, get height of the window(using global innerHeight) and subtract from the total scrollable height(document.body.scrollHeight). By dividing pageYOffset(the current scroll position), by the maximum scroll position and multiplying by 100, we get the percentage for the progress bar.

Note
Calling preventDefault on a scroll event does not prevent the scrolling from happening. The event handler is called only after the scrolling takes place.
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +