Scroll timeline using javascript

Scroll Me progress for content javascript (1)

Hi 🙂 Today in this tutorial, We’ll discuss a timeline for scroll content using javascript. In most blogs like HubSpot, Cricinfo shows how long reader need to scroll scrolled within the page by which they can identify the content height and how long need to read.(To know how long the content is and how long readers read). Let see how to create a timeline for scroll content with javascript.

Demo

Into this Code

  1. HTML
  2. CSS
  3. Javascript

How is it working?

The simple concept behind the scroll timeline is by changing CSS width property to the progress element. Width is cis calculated using scroll content height, scroll top and scroll content outer height. The final value is to convert into percentage apply to the progress element.

HTMLElement

Add scroll container, progress element

<div class=”container”>
<div class=”scrollProgress” id=”scrollProgress”></div>
<div class=”listContainer” id=”listContainer”>
<ul class=”listUL” id=”listUL”>
<li>Scroll Me</li>
<li>Scroll Me</li>
.

.

.
<li>Scroll Me</li>

</ul>
</div>
</div>

Javascript

Bind scroll event to the scroll container, In demo listContainer, is the scroll container

var init = function(){
scrollProgress = document.getElementById(“scrollTimeline”);
listContainer = document.getElementById(“listContainer”);
listUL = document.getElementById(“listUL”);

listContainer.addEventListener(“scroll”, scrollMe, false);
}

Calculate progress bar width and apply to the progress element.

var scrollTop = listContainer.scrollTop;
var totalHeight = listUL.clientHeight – listContainer.clientHeight;
var percent = scrollTop/totalHeight*100;
scrollProgress.style.width = percent+”%”;

Demo

Thank you for reading this tutorial, and if you have any question or related work to show, please do. ?

You may also like