html
<div class="progress-bar" id="progressBar"></div>
script
<script>
function progressBar() {
let scroll = document.body.scrollTop || document.documentElement.scrollTop;
let height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
let scrolled = scroll / height * 100;
document.getElementById('progressBar').style.width = scrolled + '%';
console.log(scrolled);
if (scrolled == 100);
progressBar.style.backgroundColor = "green";
}
window.addEventListener('scroll', progressBar);
</script>
I need to change the color of the progressBar from red to green when i scroll to the bottom, but for some reason i get TypeError when i try to change background color
Uncaught TypeError: Cannot set properties of undefined (setting 'backgroundColor')
at progressBar (index.html:144)
Several issues
const bar = document.getElementById('progressBar');
function progressBar() {
let scroll = document.body.scrollTop || document.documentElement.scrollTop;
let height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
let scrolled = scroll / height * 100;
bar.style.width = scrolled + '%';
if (scrolled == 100) bar.style.backgroundColor = "green";
}
window.addEventListener('scroll', progressBar);
.progress-bar {
background-color: red;
height: 20px;
width: 0px;
position: fixed;
}
<div class="progress-bar" id="progressBar"></div>
<p>X<br /></p>
<p><br /></p>
<p><br /></p>
<p><br /></p>
<p><br /></p>
<p><br /></p>
<p><br /></p>
<p><br /></p>
<p><br /></p>
<p><br /></p>
<p><br /></p>
<p><br /></p>
<p><br /></p>
<p><br /></p>
<p><br />X</p>
Wrong here : if (scrolled == 100);,remove the semicolon.
Also here progressBar.style.backgroundColor = "green"; progressBar here is the function not the progress Bar element (DOM element), and also you shouldn't do this document.getElementById('progressBar').style.width = scrolled + '%';
instead assign the progress bar element to a variable (variable's name SHOULD NOT be same as the function) and then use it inside the function like this:
<script>
let progressBarElement = document.getElementById("progressBar");
function progressBarFunction() {
let scroll =
document.body.scrollTop || document.documentElement.scrollTop;
let height =
document.documentElement.scrollHeight -
document.documentElement.clientHeight;
let scrolled = Math.floor((scroll / height) * 100);
progressBarElement.style.width = scrolled + "%";
if (scrolled >= 100)
progressBarElement.style.backgroundColor = "green";
console.log(scrolled);
}
window.addEventListener("scroll", progressBarFunction);
</script>
The style for the progressBar:
<style>
#progressBar {
position: fixed;
height: 5px;
background-color: orange;
}
</style>