Reputation: 13
I made a multi section landing page with a navbar containing the links to the sections of the page I need to give an active class to the link of the section closest to the top of the page, I tried using the scroll event listener but it is not working properly
//respond to scrolling by giving navbar active state for current section
``document.addEventListener("scroll", function() {
const scrollPos = document.body.scrollTop;
let pos = 0;
for (let i = 0; i < sec.length; i++) {
// determining pos of current section
pos+=sec[i].offsetHeight ;
let secPos = sec[i].getBoundingClientRect().y;
secPos - scrollPos <= 0 && secPos + pos >= scrollPos ? list[i].classList.add("active") : list[i].classList.remove("active")
}
});```
Upvotes: 1
Views: 40
Reputation: 29369
The scroll event is working properly, but your code does not correctly address the list of elements you are itering.
just try changing list[]
to sec[]
document.addEventListener( "DOMContentLoaded", function() {
let sec = document.querySelectorAll('section');
console.log(sec);
sec[0].classList.add("active")
document.addEventListener("scroll", function() {
const scrollPos = document.body.scrollTop;
let pos = 0;
for (let i = 0; i < sec.length; i++) {
// determining pos of current section
pos+=sec[i].offsetHeight ;
let secPos = sec[i].getBoundingClientRect().y;
if ((secPos - scrollPos <= 0) && (secPos + pos >= scrollPos))
sec[i].classList.add("active");
else
sec[i].classList.remove("active");
}
})
})
section {
font-size: 80px;
text-align: center;
width: 300px;
margin: 20px auto;
background-color: pink;
border: 1px solid red;
}
section.active {
border: 1px solid blue;
background-color: cyan;
}
<section>1</section>
<section>2</section>
<section>3</section>
<section>4</section>
<section>5</section>
<section>6</section>
<section>7</section>
<section>8</section>
Upvotes: 0