Scrollable page
by Hemant Sharma
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Scrollable Page</title>
</head>
<body>
<div class="progressbarContainer">
<div class="progressbar"></div>
</div>
<ul>
<li class="active"></li>
<li></li>
<li></li>
<li></li>
</ul>
<div class="conatiner">
<main>
<section>Section 1</section>
<section>Section 2</section>
<section>Section 3</section>
<section>Section 4</section>
</main>
</div>
</body>
</html>
CSS
body {
margin: 0;
}
.progressbarContainer {
height: 2px;
position: fixed;
top: 0;
width: 100%;
}
.progressbar {
height: 2px;
position: absolute;
width: 25%;
background: #481256;
color: #000;
}
.container {
width: 75%;
background: #eee;
margin: 0 a
}
section {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
font-family: cursive;
background: #9ab1f1;
}
section:nth-child(2) {
background: #b2e0b4;
}
section:nth-child(3) {
background: #f7d7d7;
}
section:nth-child(4) {
background: #c7c7c7;
}
ul {
margin: 0;
padding: 0;
list-style: none;
position: fixed;
top: 50%;
transform: translateY(-50%);
right: 20px;
}
li {
height: 10px;
width: 10px;
background: #eee;
margin-top: 10px;
border-radius: 15px;
border: 2px solid #808080;
transition: all 0.5s
}
li:hover, li.active {
transform: scale(1.4);
}
JavaScript
function resetSelector(){
const navItems = document.querySelectorAll("li");
navItems.forEach(function(item){
item.classList.remove("active");
});
}
const windowH = window.innerHeight;
window.addEventListener("scroll", function(){
const scrollTop = window.scrollY;
const sections = document.querySelectorAll("section");
const navItems = document.querySelectorAll("li");
sections.forEach(function(section, i){
if(section.offsetTop < scrollTop + windowH/2 && scrollTop < section.offsetTop + windowH/2){
resetSelector();
navItems[i].classList.add("active");
const pbar = document.querySelector(".progressbar");
if(i === 0)
pbar.style.width = '25%';
else if(i === 1)
pbar.style.width = '50%';
else if(i === 2)
pbar.style.width = '75%';
else
pbar.style.width = '100%';
}
})
});