Introduction
In this lab, we will explore how to create a scroll progress bar using HTML, CSS, and JavaScript. The scroll progress bar is a great way to indicate the user's current position on the page and how much more content is left to be seen. By the end of this lab, you will have a better understanding of how to implement this feature on your website.
Scroll Progress Bar
index.html and style.css have already been provided in the VM.
To create a progress bar that shows the scroll percentage of a webpage, follow these steps:
- Add a
divelement with theid"scroll-progress" to the HTML code. - In the CSS code, set the
positionof the element tofixed, thetopto0, thewidthto0%, theheightto4px, and thebackgroundcolor to#7983ff. - Set the
z-indexvalue to a large number to ensure that the progress bar is placed at the top of the page and above any content. - In the JavaScript code, select the
scroll-progresselement using thedocument.getElementById()method. - Calculate the height of the webpage using the formula
document.documentElement.scrollHeight - document.documentElement.clientHeight. - Add an event listener to the
windowobject that listens for thescrollevent. - In the event listener function, calculate the scroll percentage of the document using the formula
(scrollTop / height) * 100. - Set the
widthof thescroll-progresselement to the scroll percentage using thestyleproperty.
Here is the code:
<div id="scroll-progress"></div>
#scroll-progress {
position: fixed;
top: 0;
width: 0%;
height: 4px;
background: #7983ff;
z-index: 10000;
}
const scrollProgress = document.getElementById("scroll-progress");
const height =
document.documentElement.scrollHeight - document.documentElement.clientHeight;
window.addEventListener("scroll", () => {
const scrollTop =
document.body.scrollTop || document.documentElement.scrollTop;
scrollProgress.style.width = `${(scrollTop / height) * 100}%`;
});
Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.
Summary
Congratulations! You have completed the Scroll Progress Bar lab. You can practice more labs in LabEx to improve your skills.